How to Implement Server-Side Rendering (SSR) in React
Server-Side Rendering (SSR) is a technique where your React components are rendered on the server instead of the browser. This improves performance, SEO, and initial load time, making it ideal for content-heavy or public-facing applications.
Basic Steps to Implement SSR in React:
-
Set up a Node.js server (commonly with Express)
Your server will handle incoming requests and render React components into HTML before sending them to the client. -
Install necessary dependencies
You will need:npm install express react react-dom react-dom/server
react-dom/server
provides methods likerenderToString()
to convert React components into HTML strings.
-
Create a server file (e.g.,
server.js
)import express from "express"; import React from "react"; import { renderToString } from "react-dom/server"; import App from "./App"; // Your main React App component import fs from "fs"; import path from "path"; const app = express(); app.use(express.static("./build")); // serve static files like CSS, JS app.get("*", (req, res) => { const appString = renderToString(<App />); // Read the base HTML file const indexFile = path.resolve("./build/index.html"); fs.readFile(indexFile, "utf8", (err, data) => { if (err) { console.error("Error reading index.html:", err); return res.status(500).send("Server error"); } // Inject the server-rendered app into the HTML return res.send( data.replace('<div id="root"></div>', `<div id="root">${appString}</div>`) ); }); }); app.listen(3000, () => { console.log("Server is listening on port 3000"); });
-
Build your React App
Before running your server, make sure you build your React app:npm run build
-
Run the server
Start your custom Node.js server (instead ofnpm start
):node server.js
Important Notes:
-
Hydration: On the client side, React needs to take over the server-rendered HTML. Use
ReactDOM.hydrate()
instead ofReactDOM.render()
in your entry point (index.js
).import { hydrate } from "react-dom"; import App from "./App"; hydrate(<App />, document.getElementById("root"));
-
Routing: For full SSR apps, use libraries like
react-router-dom
withStaticRouter
on the server. -
Data Fetching: Server-side needs to fetch all necessary data before rendering. Libraries like
Next.js
or custom solutions handle this better. -
Better Option: Frameworks like Next.js automate a lot of this setup and are the industry standard for production SSR apps in React.
Summary:
Implementing SSR in React involves creating a server that renders your app into HTML using renderToString
, sending that HTML to the client, and hydrating it on the browser side. While you can set it up manually for learning purposes, in production, using frameworks like Next.js is highly recommended.