Skip to content
Tutorials Center
My learning

Topics

Lesson 85 of 132 ยท Routing and Apps

Server-Side Rendering and Hydration

Learn server-side rendering in React - renderToString, hydrateRoot, hydration mismatches and how to fix them, streaming with Suspense, static generation, and the SEO and speed trade-offs.

A client-side React app sends the browser an empty page and a bundle. Until the bundle has downloaded, parsed and run, the visitor sees a blank screen, and a search engine crawler that does not run JavaScript sees nothing at all. Server-side rendering (SSR) fixes this by running your components on a server first and sending real HTML. The visitor sees content immediately; React then "wakes up" the HTML in the browser, a step called hydration.

You will learn the two halves of that story with code you can run here, because react-dom/server works inside the editor: turning components into HTML strings with renderToString, attaching React to existing HTML with hydrateRoot, why a mismatch between the two is a bug, how streaming with Suspense sends the page in pieces, and how static generation relates. You will also see where this fits among frameworks (see Server Components, Server Functions and Frameworks).

Almost nobody wires SSR by hand in production: frameworks such as Next.js, React Router in framework mode, Remix or TanStack Start do the server, bundling and routing parts. But every one of them is built from the functions in this lesson, and almost every SSR bug is a hydration bug, so understanding the mechanism pays off.

Client rendering versus server rendering

Client-side rendering Server-side rendering
First HTML from the server Almost empty (<div id="root"></div>) The full page content
When users see content After JS downloads and runs As soon as the HTML arrives
Interactivity When rendering finishes After hydration (the HTML is visible before this)
Crawlers and link previews Need to run JavaScript Get content directly
Server cost Static files only A render on every request (or at build time)
Complexity Low Higher: code must run in two places

SSR does not make your app faster in every way. It improves how soon users see content (First Contentful Paint, Largest Contentful Paint), but they still wait for JavaScript before they can use it. A page that looks ready but ignores clicks for two seconds can feel worse than a spinner. We come back to that in the trade-offs section.

renderToString: components to HTML

The server half is a function that takes an element and returns a string of HTML. The React DOM server entry point is react-dom/server.

renderToString

Three things to notice in the output:

  • It is plain HTML. The onClick handler is not in it, because functions cannot be written into HTML. Nothing is interactive yet.
  • The hostile text in bio came out as &lt;script&gt;.... React escapes text just as it does in the browser, so server rendering is as safe against injection as client rendering (as long as you avoid dangerouslySetInnerHTML with untrusted input).
  • Effects did not run. useEffect and useLayoutEffect never execute on the server, which is why browser-only code belongs in effects (see useEffect). State setters called during a server render do nothing useful either, because the render happens once.

A real server would put that string into a document template, along with the script tags for your client bundle:

JavaScript
// server.js  (read-only sketch: runs on Node, not in the editor)
import { renderToString } from 'react-dom/server';
import { App } from './App.js';

app.get('*', (request, response) => {
  const appHtml = renderToString(<App url={request.url} />);
  response.send(`<!doctype html>
<html lang="en">
  <head><title>My app</title></head>
  <body>
    <div id="root">${appHtml}</div>
    <script type="module" src="/client.js"></script>
  </body>
</html>`);
});

renderToString or renderToStaticMarkup?

renderToStaticMarkup produces HTML without the extra markers that hydration needs. It suits emails, RSS feeds or PDFs, where there is no client React. Never use it for a page you plan to hydrate.

Hydration markers

The first string contains <!-- --> comments between the text pieces. They separate text nodes that React created separately (Total: , 5, dollars), so the client can match them one for one with the DOM. The static version merges everything into one text node and has no such markers.

hydrateRoot: attaching React to existing HTML

On the client, you do not call createRoot(...).render(...) for server-rendered markup, because that would throw the HTML away and rebuild it. You call hydrateRoot(container, <App />). React then renders your component tree in memory, walks the existing DOM in parallel, reuses each node it finds, and attaches event handlers. It does not create DOM; it adopts it.

JSX
// client.js  (read-only sketch: shown in a real project)
import { hydrateRoot } from 'react-dom/client';
import { App } from './App.js';

hydrateRoot(document.getElementById('root'), <App url={location.pathname} />);

The demo below plays both roles on one page: it fills #root with server HTML, then hydrates it. It checks the very same <button> element before and after to prove React reused it.

Hydrating server HTML

The console reports that before hydration the button had no React data, afterwards it does, and it is the same DOM node. Click the button: it counts up from 5 because the client rendered the same Counter with the same start. That is the contract.

hydrateRoot also takes an onRecoverableError option (as used above). React calls it whenever it had to recover from something that did not match. In production, send these to your error tracker: they are bugs even though the page keeps working.

The golden rule: server and first client render must match

During hydration React expects the HTML it finds to be what its own render would have produced. If the two disagree, React cannot trust the existing DOM. In React 19 it reports a recoverable error and, in many cases, throws away the affected part of the server HTML and renders it again on the client. The page ends up correct, but you lose the speed benefit and you may see a flicker.

Typical causes:

  • Browser-only checks in render: typeof window !== 'undefined', window.innerWidth, navigator.language, localStorage.
  • Values that change between renders: Date.now(), new Date(), Math.random(), or a time zone difference between server and user.
  • Invalid HTML nesting: a <div> inside a <p>, or a <table> without <tbody> handled differently by the browser parser than by React's string.
  • Browser extensions or third-party scripts that modify the HTML before React loads.
  • Different data on the server and in the client (for example the client fetched newer data).

Here is a deliberate mismatch. The component asks "where am I running?" during render, so the server prints one word and the client another:

A hydration mismatch (fails on purpose)

Run it and read the console. React reports Hydration failed because the server rendered text didn't match the client. As a result this tree will be regenerated on the client. The error text goes on to list the usual causes. The final page reads "Rendered in the browser": React repaired it by rendering on the client, but the server work was wasted for that part of the page.

Fixing mismatches

The fix depends on the cause, but there are two main techniques.

1. Render the same thing first, then update after hydration. Use state and an effect. Effects run only in the browser, after hydration, so the first client render matches the server HTML exactly and the second render shows the real value:

Two-pass rendering

This time there is no recoverable error: the log shows the server HTML, then the updated text after hydration. The cost is a visible change from the placeholder to the real value, so choose a placeholder of the same size to avoid layout shift.

2. Make the value the same on both sides. Pass server-computed values (the current time, the user's locale, a random seed) to the client as props or as serialized initial data, or generate ids with useId, which is designed to produce matching values on the server and client (the exact string is an implementation detail; never rely on it). For subscriptions to external data like matchMedia, use useSyncExternalStore with a getServerSnapshot argument (see External Stores).

3. As a last resort, suppress the warning for one element where a difference is intentional and harmless (a timestamp), using suppressHydrationWarning on that element. It applies only one level deep and only to text or attribute differences; it does not fix anything, it silences the check.

JSX
<time dateTime={iso} suppressHydrationWarning>{formatLocalTime(iso)}</time>

Streaming SSR with Suspense

renderToString has a weakness: it must finish the whole page before it can send a single byte. If one component waits for a slow database query, every visitor waits for it. Streaming solves this. The server sends the HTML shell immediately, with a fallback in place of each slow part (a Suspense boundary), and sends the finished content later in the same response. A tiny inline script swaps the fallback for the real content, and React hydrates each part independently as it arrives.

In the browser build of react-dom/server, the streaming function is renderToReadableStream. On Node.js the equivalent is renderToPipeableStream, and both give you a stream you can pipe into the HTTP response. This demo reads the chunks and prints how they look:

Reading a streamed render

The first chunk holds <h1>Dashboard</h1> and the loading report... fallback inside Suspense markers. The second chunk, sent about 60 milliseconds later, contains the finished <b>Late data</b> in a hidden div plus a small script that moves it into place. In production this means a slow widget no longer blocks the rest of the page.

Streaming also improves hydration. React can hydrate the parts that have arrived and prioritize the part the user clicks first (selective hydration), instead of hydrating the whole page in one long task.

Static generation versus server rendering

SSR does not have to happen per request. The same render functions can run at build time to produce plain HTML files, and that is called static site generation (SSG):

Approach When HTML is produced Best for Watch out for
Client rendering (CSR) In the browser Logged-in dashboards, internal tools Slow first paint, weak SEO
Static generation (SSG) At build time Docs, blogs, marketing pages Rebuilds when content changes
Incremental static regeneration At build time, refreshed in the background Large content sites Stale content window
Server rendering (SSR) On every request Personalized or frequently changing pages Server cost, slower TTFB
Streaming SSR On every request, in pieces Pages with slow sections Needs Suspense-aware data loading

Static HTML can be cached on a CDN and served in milliseconds anywhere, which is hard to beat for content that is the same for everyone. Many sites mix strategies per route: static marketing pages, server-rendered product pages, client-rendered account area. Frameworks let you choose per route.

SEO and performance trade-offs

  • SEO: Googlebot does run JavaScript, but rendering is deferred and other crawlers and link-preview bots often do not run it. With SSR or SSG, titles, headings, text and metadata are in the first response. Combine it with proper <title>, meta description and canonical links (React 19 can hoist these from components).
  • Time to First Byte (TTFB): SSR adds server work before the first byte. Streaming and caching reduce the cost.
  • Interactivity gap: the page is visible before it is interactive. Keep client bundles small, split code, hydrate below-the-fold parts later, and avoid heavy work in effects on load.
  • Double work: every component runs on the server and again on the client at hydration. This is one of the motivations for Server Components, which skip the second run for components that need no interactivity.
  • Server-only data in HTML: the serialized initial data you embed for the client is public. Do not include secrets or other users' data.

Writing SSR-safe components

A short checklist for any component that might run on the server:

  • Do not touch window, document, localStorage or navigator during render. Put them in effects or event handlers.
  • Do not read the current time or random numbers during render; pass them in or derive them after mount.
  • Keep render pure (see Pure Components): same props and state, same output.
  • Use useId for ids that link labels and inputs.
  • Load the same data on both sides, then hand it to the client as initial state.
  • Use valid HTML nesting; browsers silently rearrange invalid markup, which creates mismatches.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does hydrateRoot do?

    Hydration adopts existing HTML instead of recreating it, so users see content before JavaScript has run and the page becomes interactive afterwards.
  2. 2. Why is <p>{Date.now()}</p> in a component a problem for server-rendered pages?

    The server computes the time once and the client computes another time later. The first client render must match the server HTML, so values like this must be passed in or set after mount.
  3. 3. Which tool should you use to produce HTML for an email that will never be hydrated?

    renderToStaticMarkup creates clean HTML without markers. It is not suitable for pages that React will hydrate.
  4. 4. What is the main benefit of streaming SSR with Suspense?

    Each Suspense boundary can resolve on its own, so one slow data source does not delay the whole page.
  5. 5. A component reads window.innerWidth during render and causes a hydration warning. What is a good fix?

    Effects run only in the browser after hydration, so the first client render matches the server output and the real value is applied afterwards.

Summary

  • SSR runs components on a server to send real HTML first; hydration then attaches React to that HTML in the browser.
  • renderToString produces HTML with hydration markers; renderToStaticMarkup does not and is for non-hydrated output. Effects and event handlers do not run on the server.
  • hydrateRoot reuses the existing DOM and attaches handlers, and onRecoverableError reports problems.
  • The first client render must produce the same output as the server. Avoid browser-only values, time, randomness and invalid HTML nesting during render; use effects, props or useId.
  • Streaming (renderToPipeableStream on Node, renderToReadableStream on web streams) sends the shell early and fills Suspense boundaries as data arrives, with selective hydration on the client.
  • Static generation does the render at build time and is best for content that is the same for everyone; frameworks mix SSG, SSR and CSR per route.
  • SSR helps SEO and perceived loading speed but adds server work and an interactivity gap you must manage.

Next: Testing React Components