Create React App and React Scripts projects are probably the most well-known way to quickly set up the React-based application. The motto of the project is 100% no configuration, everything is based on convention. This is a fairly robust solution that has everything you need except for the Server Side Rendering support.
First of all, let’s install the required packages:
Add file or “babel” section to
The presetis installed along with , but for server rendering we need to refer to it directly.
React Router’s endpoint page
Just like before, the essence of Server Side Rendering is to determine which page has to be displayed based on router’s routes, figure out which data this page needs, load it, render HTML and send it along with the data to the client.
Server takes the endpoint page, calls its, inside of which we can dispatch some Redux actions and return the initial set of props (if Redux is not used). This method will be called on a client too (not if server has sent data though), which greatly simplifies the initial data load procedure.
The propwill have value if raised an exception.
The page that will be used as 404 stub should have static property:
The functionshould return routes for React Router, async routes are also supported, but for simplicity let’s skip them:
The functionshould take the initial state as an argument and return a new instance of :
Additional parameters with NodeJS Request and Response will be added when function is used on a server, they can be used to create an initial state from scratch because first parameter will bein this case.
Main app entry point
Now let’s put everything together:
Start the server using simple CLI
We need to add a sectionto :
Now we can build & start the server:
If we openin browser we will see the page that has been rendered by the server. If you change the route then client side will take care of all data for the page.
In this mode the server-side build is not saved, it is dynamically created every time the server is started.
Start the server using API
If the CLI server is not flexible enough or if you decide to keep the server build then you can use the API.
In addition to previously installed packages let’s install, it will be used to build the server:
Add following commands tosection of :
The client part will still be built by Create React App (React Scripts), but the server with Babel, which will take everything fromand put the result in .
If we openin browser we will see the same page that still has been rendered by the server.