Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 862
Rohit Jamuar Avatar asked Aug 01 '26 02:08

Rohit Jamuar


1 Answers

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:

  • Follow this guide: https://medium.com/bucharestjs/upgrading-a-create-react-app-project-to-a-ssr-code-splitting-setup-9da57df2040a
  • If you don't understand anything in that guide, learn from this course: https://www.youtube.com/playlist?list=PLMhLdUN2ZKJ2f-QDFBP1iphsmPd81MQOO
like image 78
Phuoc Do Avatar answered Aug 02 '26 16:08

Phuoc Do



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!