How we can convert client side rendering react js app to server side rendering using react router 4?
Asked Answered
C

1

7

How we can convert client-side rendering react js app to server-side rendering using react-router 4?

Crunch answered 5/3, 2021 at 18:3 Comment(0)
M
8

Assuming you are using Create React App with React Router 4, you'll need to do the following steps:

  • Create an SSR server: Add a root/server/index.jsx that contains your Express server, serving the default setup of CRA as documented here: https://create-react-app.dev/docs/deployment#other-solutions
  • Render your app on server: Import your src/App.jsx component in your server/index.jsx, use ReactDOMServer.renderToString(<App/>) to render your app to a string, then inject it into the build/index.html, and res.send the injected HTML to the browser upon a request.
  • Try to run your server: node server/index.jsx does not work because node does not understand JSX. You'll need to setup webpack with babel to transpile your server/index.jsx, and then run the transpiled file with node. Because your server code imports src/App.jsx, which may also import css, svg, png, jpg, etc. files, you'll get a lot of errors running your server. Fix errors one by one by configuring your webpack to suit your use cases.
  • Hydrate your app on client: After successfully running your server, try to send a request from a browser. You may see a blank page but don't worry because we have not rendered correctly on the server yet. However, let's assume that your server did render something on step 2 above. Then, when your browser receives the HTML page, it just needs to make interactive components like buttons work properly. To do this, edit file src/index.js to use ReactDOM.hydrate() instead of ReactDOM.render().
  • Render route-based content correctly on server-side: Keep using BrowserRouter in src/index.js, but in server/index.js on server-side, use StaticRouter instead and pass req.originalUrl to that StaticRouter. This is because BrowserRouter read address from your browser address bar, but the server does not have an address bar.
  • Getting correct data on server: server-side does not execute componentDidMount, comonentDidUpdate, and useEffect hook. Only render() function will be executed. Therefore, create hooks to query your data on server-side.

Recommendations if you want to add SSR for CRA:

Marcelenemarcelia answered 5/3, 2021 at 21:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.