The most common use case for server-side rendering is to handle the initial render when a user (or search engine crawler) first requests our app. When the server receives the request, it renders the required component(s) into an HTML string, and then sends it as a response to the client. From that point on, the client takes over rendering duties.
We will use React in the examples below, but the same techniques can be used with other view frameworks that can render on the server.
When using Redux with server rendering, we must also send the state of our app along in our response, so the client can use it as the initial state. This is important because, if we preload any data before generating the HTML, we want the client to also have access to this data. Otherwise, the markup generated on the client won't match the server markup, and the client would have to load the data again.
To send the data down to the client, we need to:
- create a fresh, new Redux store instance on every request;
- optionally dispatch some actions;
- pull the state out of store;
- and then pass the state along to the client.
On the client side, a new Redux store will be created and initialized with the state provided from the server. Redux's only job on the server side is to provide the initial state of our app.
In the following recipe, we are going to look at how to set up server-side rendering. We'll use the simplistic Counter app as a guide and show how the server can render state ahead of time based on the request.
For this example, we'll be using Express as a simple web server. We also need to install the React bindings for Redux, since they are not included in Redux by default.
The following is the outline for what our server side is going to look like. We are going to set up an Express middleware using app.use to handle all requests that come in to our server. If you're unfamiliar with Express or middleware, just know that our handleRender function will be called every time the server receives a request.
The first thing that we need to do on every request is to create a new Redux store instance. The only purpose of this store instance is to provide the initial state of our application.
When rendering, we will wrap
<App />, our root component, inside a
<Provider> to make the store available to all components in the component tree, as we saw in "Redux Fundamentals" Part 5: UI and React.
The key step in server side rendering is to render the initial HTML of our component before we send it to the client side. To do this, we use ReactDOMServer.renderToString().
We then get the initial state from our Redux store using
store.getState(). We will see how this is passed along in our
The final step on the server side is to inject our initial component HTML and initial state into a template to be rendered on the client side. To pass along the state, we add a
<script> tag that will attach
preloadedState will then be available on the client side by accessing
We also include our bundle file for the client-side application via a script tag. This is whatever output your bundling tool provides for your client entry point. It may be a static file or a URL to a hot reloading development server.
The client side is very straightforward. All we need to do is grab the initial state from
window.__PRELOADED_STATE__, and pass it to our
createStore() function as the initial state.
Let's take a look at our new client file:
You can set up your build tool of choice (Webpack, Browserify, etc.) to compile a bundle file into
When the page loads, the bundle file will be started up and
ReactDOM.hydrate() will reuse the server-rendered HTML. This will connect our newly-started React instance to the virtual DOM used on the server. Since we have the same initial state for our Redux store and used the same code for all our view components, the result will be the same real DOM.
And that's it! That is all we need to do to implement server side rendering.
But the result is pretty vanilla. It essentially renders a static view from dynamic code. What we need to do next is build an initial state dynamically to allow that rendered view to be dynamic.
Because the client side executes ongoing code, it can start with an empty initial state and obtain any necessary state on demand and over time. On the server side, rendering is synchronous and we only get one shot to render our view. We need to be able to compile our initial state during the request, which will have to react to input and obtain external state (such as that from an API or database).
The only input for server side code is the request made when loading up a page in your app in your browser. You may choose to configure the server during its boot (such as when you are running in a development vs. production environment), but that configuration is static.
The request contains information about the URL requested, including any query parameters, which will be useful when using something like React Router. It can also contain headers with inputs like cookies or authorization, or POST body data. Let's see how we can set the initial counter state based on a query parameter.
The code reads from the Express
Request object passed into our server middleware. The parameter is parsed into a number and then set in the initial state. If you visit http://localhost:3000/?counter=100 in your browser, you'll see the counter starts at 100. In the rendered HTML, you'll see the counter output as 100 and the
__PRELOADED_STATE__ variable has the counter set in it.
The most common issue with server side rendering is dealing with state that comes in asynchronously. Rendering on the server is synchronous by nature, so it's necessary to map any asynchronous fetches into a synchronous operation.
The easiest way to do this is to pass through some callback back to your synchronous code. In this case, that will be a function that will reference the response object and send back our rendered HTML to the client. Don't worry, it's not as hard as it may sound.
For our example, we'll imagine there is an external datastore that contains the counter's initial value (Counter As A Service, or CaaS). We'll make a mock call over to them and build our initial state from the result. We'll start by building out our API call:
Again, this is just a mock API, so we use
setTimeout to simulate a network request that takes 500 milliseconds to respond (this should be much faster with a real world API). We pass in a callback that returns a random number asynchronously. If you're using a Promise-based API client, then you would issue this callback in your
On the server side, we simply wrap our existing code in the
fetchCounter and receive the result in the callback:
Because we call
res.send() inside of the callback, the server will hold open the connection and won't send any data until that callback executes. You'll notice a 500ms delay is now added to each server request as a result of our new API call. A more advanced usage would handle errors in the API gracefully, such as a bad response or timeout.
Because we have introduced more code that relies on user generated content (UGC) and input, we have increased our attack surface area for our application. It is important for any application that you ensure your input is properly sanitized to prevent things like cross-site scripting (XSS) attacks or code injections.
In our example, we take a rudimentary approach to security. When we obtain the parameters from the request, we use
parseInt on the
counter parameter to ensure this value is a number. If we did not do this, you could easily get dangerous data into the rendered HTML by providing a script tag in the request. That might look like this:
For our simplistic example, coercing our input into a number is sufficiently secure. If you're handling more complex input, such as freeform text, then you should run that input through an appropriate sanitization function, such as xss-filters.
Furthermore, you can add additional layers of security by sanitizing your state output.
JSON.stringify can be subject to script injections. To counter this, you can scrub the JSON string of HTML tags and other dangerous characters. This can be done with either a simple text replacement on the string, e.g.
You may want to read Redux Fundamentals Part 6: Async Logic and Data Fetching to learn more about expressing asynchronous flow in Redux with async primitives such as Promises and thunks. Keep in mind that anything you learn there can also be applied to universal rendering.
If you use something like React Router, you might also want to express your data fetching dependencies as static
fetchData() methods on your route handler components. They may return thunks, so that your
handleRender function can match the route to the route handler component classes, dispatch
fetchData() result for each of them, and render only after the Promises have resolved. This way the specific API calls required for different routes are colocated with the route handler component definitions. You can also use the same technique on the client side to prevent the router from switching the page until its data has been loaded.