Mark As Completed Discussion

Server-Side Rendering with React Router

Server-side rendering (SSR) is a technique that allows us to render React components on the server and send the generated HTML to the client. This can improve the initial loading time of our application and provide better SEO results.

To implement SSR with React Router, we can use a server framework like Express and the StaticRouter from react-router-dom.

Here's an example of how we can implement SSR with React Router:

JAVASCRIPT
1// Example of server-side rendering with React Router
2
3const express = require('express');
4const React = require('react');
5const ReactDOMServer = require('react-dom/server');
6const { StaticRouter } = require('react-router-dom');
7
8const App = require('./App');
9
10const server = express();
11
12server.get('*', (req, res) => {
13  const context = {};
14  const app = ReactDOMServer.renderToString(
15    React.createElement(
16      StaticRouter,
17      { location: req.url, context: context },
18      React.createElement(App)
19    )
20  );
21
22  if (context.url) {
23    res.redirect(context.url);
24  } else {
25    res.send(`
26      <!DOCTYPE html>
27      <html>
28        <head>
29          <title>Server Side Rendered App</title>
30        </head>
31        <body>
32          <div id='app'>${app}</div>
33          <script src='/bundle.js'></script>
34        </body>
35      </html>
36    `);
37  }
38});
39
40server.listen(3000, () => {
41  console.log('Server is running on port 3000');
42})
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment