React Router is a popular library used for client-side routing in React applications. However, it can also be used for server-side rendering (SSR) to boost the efficiency of our application. SSR is a technique that allows your web pages to be rendered on the server before being sent to the client.
This method offers a number of advantages, including faster initial load times, enhanced SEO, and greater accessibility. You must configure your server to process incoming requests and render the relevant React components before you can use React Router for SSR. To build up our server in this example, we'll use Node.js and Express.
Here is an example of server-side rendering script using React Router:
const express = require('express');const React = require('react');const ReactDOMServer = require('react-dom/server');const { StaticRouter, matchPath } = require('react-router-dom');const App = require('./App');const app = express();// Serve static assetsapp.use(express.static('public'));// Route handler for server-side renderingapp.get('*', (req, res) => {const context = {};const html = ReactDOMServer.renderToString(<StaticRouter location={req.url} context={context}><App /></StaticRouter>);// Check if any of the routes matched the request URLconst match = routes.find((route) => matchPath(req.url, route));// If a route matched, set the status code to 200if (match) {res.status(200);}// Send the HTML string to the clientres.send(`<!DOCTYPE html><html><head><title>React Router SSR Example</title></head><body><div id="root">${html}</div><script src="/bundle.js"></script></body></html>`);});app.listen(3000, () => {console.log('Server listening on port 3000');});
Let's go through the code step by step to understand how it works:
Lines 1–5: We import the necessary dependencies for building our server. We'll use Express as our web framework, React
and ReactDOMServer
for rendering the React components, StaticRouter
for server-side routing, and matchPath
for matching the incoming request with the appropriate React component.
Lines 7–10: We initialize the Express app and serve static assets (like CSS or images) located in the public
directory.
Lines 13–19: We add a route handler for server-side rendering.
Lines 22–26: After the rendering process is complete, it checks if any of the routes defined in the routes
array match the requested URL using the matchPath()
function. If a match is found, the HTTP status code of the response is set to 200
, indicating that the request was successful.
Lines 30–42: When the response is sent to the client, the browser will receive the HTML content, along with the JavaScript bundle file. The browser will then execute the JavaScript code in the bundle file, which will attach the React components to the DOM and make the web application interactive.
Lines 44–46: The app.listen()
method is a part of the Express web framework for Node.js, which allows developers to create server-side applications and APIs using JavaScript. By listening on port 3000
, the server will be able to receive incoming requests from clients that make requests to the same port. When a request is received on this port, the server will process it according to the defined routes and return an appropriate response.
Free Resources