ReactMedium

What is SSR (Server-Side Rendering)?

Server-side rendering means generating a page's HTML on the server for each request, so the browser shows content immediately; React then hydrates that HTML in the browser to make it interactive. It improves first paint, SEO and social previews compared with client-only rendering, at the cost of server work per request.

How it works in React

  1. The server runs your components with renderToPipeableStream (Node) or renderToReadableStream (Web streams) from react-dom/server.
  2. HTML streams to the browser; <Suspense> fallbacks are sent first and replaced as data resolves.
  3. The browser displays the HTML before JavaScript loads.
  4. hydrateRoot attaches event handlers and state; selective hydration prioritizes what the user interacts with.

Benefits

  • Faster first contentful paint and LCP, especially on slow devices.
  • Crawlers and link previews get real content.
  • Data can be fetched close to the database.

Costs

  • Server CPU per request and higher time to first byte if data is slow (mitigated by streaming).
  • Code must run in both environments (no window at render time).
  • Hydration mismatches if server and client output differ.

Variants

  • Streaming SSR (React 18+): send HTML progressively.
  • SSG and ISR: render ahead of time and reuse.
  • Partial prerendering (React 19.2 prerender + resume, Next.js Cache Components): a static shell plus streamed dynamic parts.
  • Server Components: run only on the server and are not hydrated at all.

In practice

Use a framework: Next.js, React Router framework mode, TanStack Start or Expo Router (web). Writing SSR by hand is rarely worth it.

Code example

tsx
1// server.ts - minimal streaming SSR with Node.js
2import { createServer } from "node:http";
3import { renderToPipeableStream } from "react-dom/server";
4import { App } from "./app";
5
6createServer((req, res) => {
7 const { pipe } = renderToPipeableStream(<App url={req.url ?? "/"} />, {
8 bootstrapScripts: ["/client.js"],
9 onShellReady() {
10 res.setHeader("Content-Type", "text/html; charset=utf-8");
11 pipe(res); // stream HTML as Suspense boundaries resolve
12 },
13 onShellError() {
14 res.statusCode = 500;
15 res.end("<h1>Something went wrong</h1>");
16 },
17 onError(err) {
18 console.error(err);
19 },
20 });
21}).listen(3000);
22
23// client.tsx - hydrate the server HTML
24// import { hydrateRoot } from "react-dom/client";
25// hydrateRoot(document, <App url={location.pathname} />);

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app