Hello guys, welcome back! This is part 2 of the guide series on how to implement SSR to your ongoing production React product.
So in part 1 of the guide series, I showed you how I prepared the bootstrap file that will be the entry script to run our project, and by using react-app-rewired how we can override the current CRA configs to enable some Webpack configs to work with SSR.
I will be breaking this guide into 3 parts. Follow me on Twitter to get notified when the next part will come out:
In this part, I will be sharing with you 2 things:
Let's start off with creating a middleware that will be responsible for rendering all of our client-side code on the server side. Create a file renderer.jsmiddleware folder.
Let's create an empty module to start off
// middleware/renderer.js
import { StaticRouter } from "react-router-dom";
import { renderToString } from "react-dom/server";
// import our main Routes component. The main file for the project is routes.tsx
import Routes from "../../src/routes.tsx";
const path = require("path");
const fs = require("fs").promises;
// This is the module that will be responsible for most of the rendering.
export default async ctx => {
const filePath = path.resolve("build", "index.html");
let html = await fs.readFile(filePath, "utf8");
let context = {};
let component;
try {
component = renderToString(
<StaticRouter location={ctx.request.url} context={context}>
<Routes />
</StaticRouter>
);
} catch (err) {
// If something goes wrong with the component markup, this will light up.
console.log("Component Error: ", err.stack);
}
ctx.body = html
.replace(
"</head>",
`<script>window.__INITIAL_STATE__ = ${dehydratedStore}; </script></head>`
)
.replace('<div id="root"></div>', `<div id="root">${component}</div>`);
};
Okay, after cutting down most of the codes in this file, I manage to get the actual starting point from where I started when I was working on this project. We have a typical reusable middleware, let's go one by one on the stuff:
We use Node's built-in modules, fs and path (In this case, I am using an experimental module from fs which is async), and get the HTML that is generated when we run the build script.
const filePath = path.resolve("build", "index.html");
let html = await fs.readFile(filePath, "utf8");
Resolve the path build/index.html npm run build
Secondly, we import StaticRendering from react-router-dom and renderToString from react-dom/server to be used in our HTML we create a component variable that consists of these following modules. We create it as such:
const filePath = path.resolve("build", "index.html");
let html = await fs.readFile(filePath, "utf8");
let context = {};
let component;
try {
component = renderToString(
<StaticRouter location={ctx.request.url} context={context}>
<Routes />
</StaticRouter>
);
} catch (err) {
// If something goes wrong with the component markup, this will light up.
console.log("Component Error: ", err.stack);
}
Based on the documentation from React Router, to enable rendering in server side, we use StaticRouter to render our routed components in the client-side to static lines of codes, this enables the project to render any pages inside of our Router component to static when we go from page to page. There are two props needed, location and context. put in ctx.request.url ctx.url
I place the logic inside of a try...catch function so that I can catch any errors related to SSR. This is really useful when you're in development. Once you have stabilized the renderer file, you can either remove it or just leave it as is in case you want to develop more stuff in it.
ctx.body = html.replace('<div id="root"></div>', `<div id="root">${component}</div>`);
I use .replaceroot
Next, we'll go and add the middleware function into our controllers. I like to keep things neat, so in this project, I created separate folders for all the controllers needed in the server. Let's create the Index Controller and use it in our main server file.
// controllers/index.js
import Router from "koa-router";
import serverRenderer from "../middleware/renderer";
const router = new Router();
router.get("/", serverRenderer);
export default router;
Then in our server file.
// server.js
import Koa from "koa";
import Router from "koa-router";
const serve = require("koa-static");
const koa = new Koa();
const router = new Router();
//....
// Root static page.
koa.use(indexController.routes());
//...
// Public Controllers
koa
//... your other controllers
// This is the static middleware.
.use(
serve("build", {
hidden: true
})
);
//...
// Renders other routes for SSR
koa.use(serverRenderer)
//...
// This is where your server listens to port..
Make sure you are following this order when you are customizing your server file. Since Koa goes from top to bottom, it's important to have them in the correct position to reduce the errors that'll show later on as we progress.
Next, let's head over to the client-side and modify our entry file, in this project, it's src/index.tsx
// src/index.tsx
//...declare imports
//...
ReactDOM.hydrate(
<Router history={history}>
<Routes />
</Router>,
root
);
Nothing much to change here, just change ReactDOM.renderReactDOM.hydrate
Lastly, before you start running your app, go to your package.json and add/modify the script you have that starts the server
"scripts": {
"build": "react-app-rewired build",
"start": "node server/bootstrap.js" //depending on where you put your bootstrap file, in this case i have it in my server folder.
}
That is basically how I've set up the project that enables SSR. However, once you start your project, you are bound to get errors, so you can start debugging from there on, but believe me, once you've done debugging, you will understand more on how it all actually works.
Now, npm run build && npm run start
If all works, great job! You've successfully integrated SSR into your project. However, it is not the end for me, since this project is quite big, it has to have a state management framework that runs above all, assuming you already have Mobx (or any other state management framework setup on the client-side), in the next step, I won't be showing you how to set it up from scratch, but on just how to enable it to work on the server-side.
In this project, we are using Mobx as the state management framework. If you are not using Mobx as the state management framework, don't worry as we won't get into much detail on it. Regardless, they all bear the same logic, to have a global state stored somewhere in the HOC.
In Next.js, they have something called getInitialProps() where you can initialise the needed props before the client-side components hydrate in. This can include things like fetch, declaring new props and so on. In the next step, I will be doing the same thing, but better and modular.
In your renderer.js file, declare your Store and link it with a Provider component.
export default async ctx => {
// Initialize mobx store. Store will refresh everytime you jump
// onto a new page or refreshing a page.
const store = new AppStore();
// Makes mobx work with SSR
useStaticRendering(true);
const filePath = path.resolve("build", "index.html");
let html = await fs.readFile(filePath, "utf8");
// ....
// Dehydrate MobX store to be passed into client.
const dehydratedStore = stringify(toJS(store));
let context = {};
let component;
try {
component = renderToString(
<Provider store={store}>
<StaticRouter location={ctx.request.url} context={context}>
<Routes />
</StaticRouter>
</Provider>
);
} catch (err) {
// If something goes wrong with the component markup, this will light up.
console.log("Component Error: ", err.stack);
}
ctx.body = html
.replace(
"</head>",
`<script>window.__INITIAL_STATE__ = ${dehydratedStore}; </script></head>`
)
.replace('<div id="root"></div>', `<div id="root">${component}</div>`);
};
Let's go one by one:
</head>window.__INITIAL_STATE__//...
const dehydratedStore = window.__INITIAL_STATE__;
// Rehydrate store
const root = document.getElementById("root") as HTMLElement;
const store = root.hasChildNodes()
? new AppStore(dehydratedStore)
: new AppStore();
//...
ReactDOM.hydrate(
<Provider store={store}>
<Router history={history}>
<Routes />
</Router>
</Provider>,
root
);
I grabbed window.__INITIAL_STATE__
// In src/index.tsx
ReactDOM.hydrate(
<Provider store={store}>
<Router history={history}>
<Routes />
</Router>
</Provider>,
root
);
// in middleware/renderer.js
component = renderToString(
<Provider store={store}>
<StaticRouter location={ctx.request.url} context={context}>
<Routes />
</StaticRouter>
</Provider>
);
Lastly, in order for the Store to initialize the props properly, we need to add a constructor in the Store file. In this case, our project keeps all global state in app.store.tsx
class AppStore {
// ....
constructor(initialState?) {
if (initialState) {
Object.assign(this, initialState);
}
}
// .....
}
Let's add our little getInitialProps() logic into the mix. From here on, you should start on doing things based on what you want to be rendered on the server-side, in our case, we want information to be fetched even before the static page is rendered. This is so that we can eliminate a certain loading screen. So I added a section in the renderer.js for plugins.
"Plugins" is really something I come up with out of the blue. It is where you can call your own custom functions to be executed on server-side for the client-side.
However, I will have to stop here. I will continue on how to write and create custom plugins that enable us to run functions on the server-side that will populate the store for our client-side, and perhaps eliminating the loading screen
Thank you for taking the time to read the guide. This the end of Part 2. I see you in Part 3!
I will be breaking this guide into 3 parts. Follow me on Twitter to get notified when the next part will come out:
Hello guys, welcome back! This is part 2 of the guide series on how to implement SSR to your ongoing production React product.
So in part 1 of the guide series, I showed you how I prepared the bootstrap file that will be the entry script to run our project, and by using react-app-rewired how we can override the current CRA configs to enable some Webpack configs to work with SSR.
I will be breaking this guide into 3 parts. Follow me on Twitter to get notified when the next part will come out:
In this part, I will be sharing with you 2 things:
Let's start off with creating a middleware that will be responsible for rendering all of our client-side code on the server side. Create a file renderer.jsmiddleware folder.
Let's create an empty module to start off
// middleware/renderer.js
import { StaticRouter } from "react-router-dom";
import { renderToString } from "react-dom/server";
// import our main Routes component. The main file for the project is routes.tsx
import Routes from "../../src/routes.tsx";
const path = require("path");
const fs = require("fs").promises;
// This is the module that will be responsible for most of the rendering.
export default async ctx => {
const filePath = path.resolve("build", "index.html");
let html = await fs.readFile(filePath, "utf8");
let context = {};
let component;
try {
component = renderToString(
<StaticRouter location={ctx.request.url} context={context}>
<Routes />
</StaticRouter>
);
} catch (err) {
// If something goes wrong with the component markup, this will light up.
console.log("Component Error: ", err.stack);
}
ctx.body = html
.replace(
"</head>",
`<script>window.__INITIAL_STATE__ = ${dehydratedStore}; </script></head>`
)
.replace('<div id="root"></div>', `<div id="root">${component}</div>`);
};
Okay, after cutting down most of the codes in this file, I manage to get the actual starting point from where I started when I was working on this project. We have a typical reusable middleware, let's go one by one on the stuff:
We use Node's built-in modules, fs and path (In this case, I am using an experimental module from fs which is async), and get the HTML that is generated when we run the build script.
const filePath = path.resolve("build", "index.html");
let html = await fs.readFile(filePath, "utf8");
Resolve the path build/index.html npm run build
Secondly, we import StaticRendering from react-router-dom and renderToString from react-dom/server to be used in our HTML we create a component variable that consists of these following modules. We create it as such:
const filePath = path.resolve("build", "index.html");
let html = await fs.readFile(filePath, "utf8");
let context = {};
let component;
try {
component = renderToString(
<StaticRouter location={ctx.request.url} context={context}>
<Routes />
</StaticRouter>
);
} catch (err) {
// If something goes wrong with the component markup, this will light up.
console.log("Component Error: ", err.stack);
}
Based on the documentation from React Router, to enable rendering in server side, we use StaticRouter to render our routed components in the client-side to static lines of codes, this enables the project to render any pages inside of our Router component to static when we go from page to page. There are two props needed, location and context. put in ctx.request.url ctx.url
I place the logic inside of a try...catch function so that I can catch any errors related to SSR. This is really useful when you're in development. Once you have stabilized the renderer file, you can either remove it or just leave it as is in case you want to develop more stuff in it.
ctx.body = html.replace('<div id="root"></div>', `<div id="root">${component}</div>`);
I use .replaceroot
Next, we'll go and add the middleware function into our controllers. I like to keep things neat, so in this project, I created separate folders for all the controllers needed in the server. Let's create the Index Controller and use it in our main server file.
// controllers/index.js
import Router from "koa-router";
import serverRenderer from "../middleware/renderer";
const router = new Router();
router.get("/", serverRenderer);
export default router;
Then in our server file.
// server.js
import Koa from "koa";
import Router from "koa-router";
const serve = require("koa-static");
const koa = new Koa();
const router = new Router();
//....
// Root static page.
koa.use(indexController.routes());
//...
// Public Controllers
koa
//... your other controllers
// This is the static middleware.
.use(
serve("build", {
hidden: true
})
);
//...
// Renders other routes for SSR
koa.use(serverRenderer)
//...
// This is where your server listens to port..
Make sure you are following this order when you are customizing your server file. Since Koa goes from top to bottom, it's important to have them in the correct position to reduce the errors that'll show later on as we progress.
Next, let's head over to the client-side and modify our entry file, in this project, it's src/index.tsx
// src/index.tsx
//...declare imports
//...
ReactDOM.hydrate(
<Router history={history}>
<Routes />
</Router>,
root
);
Nothing much to change here, just change ReactDOM.renderReactDOM.hydrate
Lastly, before you start running your app, go to your package.json and add/modify the script you have that starts the server
"scripts": {
"build": "react-app-rewired build",
"start": "node server/bootstrap.js" //depending on where you put your bootstrap file, in this case i have it in my server folder.
}
That is basically how I've set up the project that enables SSR. However, once you start your project, you are bound to get errors, so you can start debugging from there on, but believe me, once you've done debugging, you will understand more on how it all actually works.
Now, npm run build && npm run start
If all works, great job! You've successfully integrated SSR into your project. However, it is not the end for me, since this project is quite big, it has to have a state management framework that runs above all, assuming you already have Mobx (or any other state management framework setup on the client-side), in the next step, I won't be showing you how to set it up from scratch, but on just how to enable it to work on the server-side.
In this project, we are using Mobx as the state management framework. If you are not using Mobx as the state management framework, don't worry as we won't get into much detail on it. Regardless, they all bear the same logic, to have a global state stored somewhere in the HOC.
In Next.js, they have something called getInitialProps() where you can initialise the needed props before the client-side components hydrate in. This can include things like fetch, declaring new props and so on. In the next step, I will be doing the same thing, but better and modular.
In your renderer.js file, declare your Store and link it with a Provider component.
export default async ctx => {
// Initialize mobx store. Store will refresh everytime you jump
// onto a new page or refreshing a page.
const store = new AppStore();
// Makes mobx work with SSR
useStaticRendering(true);
const filePath = path.resolve("build", "index.html");
let html = await fs.readFile(filePath, "utf8");
// ....
// Dehydrate MobX store to be passed into client.
const dehydratedStore = stringify(toJS(store));
let context = {};
let component;
try {
component = renderToString(
<Provider store={store}>
<StaticRouter location={ctx.request.url} context={context}>
<Routes />
</StaticRouter>
</Provider>
);
} catch (err) {
// If something goes wrong with the component markup, this will light up.
console.log("Component Error: ", err.stack);
}
ctx.body = html
.replace(
"</head>",
`<script>window.__INITIAL_STATE__ = ${dehydratedStore}; </script></head>`
)
.replace('<div id="root"></div>', `<div id="root">${component}</div>`);
};
Let's go one by one:
</head>window.__INITIAL_STATE__//...
const dehydratedStore = window.__INITIAL_STATE__;
// Rehydrate store
const root = document.getElementById("root") as HTMLElement;
const store = root.hasChildNodes()
? new AppStore(dehydratedStore)
: new AppStore();
//...
ReactDOM.hydrate(
<Provider store={store}>
<Router history={history}>
<Routes />
</Router>
</Provider>,
root
);
I grabbed window.__INITIAL_STATE__
// In src/index.tsx
ReactDOM.hydrate(
<Provider store={store}>
<Router history={history}>
<Routes />
</Router>
</Provider>,
root
);
// in middleware/renderer.js
component = renderToString(
<Provider store={store}>
<StaticRouter location={ctx.request.url} context={context}>
<Routes />
</StaticRouter>
</Provider>
);
Lastly, in order for the Store to initialize the props properly, we need to add a constructor in the Store file. In this case, our project keeps all global state in app.store.tsx
class AppStore {
// ....
constructor(initialState?) {
if (initialState) {
Object.assign(this, initialState);
}
}
// .....
}
Let's add our little getInitialProps() logic into the mix. From here on, you should start on doing things based on what you want to be rendered on the server-side, in our case, we want information to be fetched even before the static page is rendered. This is so that we can eliminate a certain loading screen. So I added a section in the renderer.js for plugins.
"Plugins" is really something I come up with out of the blue. It is where you can call your own custom functions to be executed on server-side for the client-side.
However, I will have to stop here. I will continue on how to write and create custom plugins that enable us to run functions on the server-side that will populate the store for our client-side, and perhaps eliminating the loading screen
Thank you for taking the time to read the guide. This the end of Part 2. I see you in Part 3!
I will be breaking this guide into 3 parts. Follow me on Twitter to get notified when the next part will come out: