What is hydration?
Related reading: SSR vs CSR vs SSG vs ISR.
The server generates HTML which the browser parses before React starts. Hydration connects that existing DOM to an interactive tree rather than independently rebuilding the application from scratch. hydrateRoot requires matching initial output. Treat mismatches as bugs even if React recovers by rendering on the client; not every mismatched attribute is guaranteed to be patched. Next.js owns the root, so do not call hydrateRoot manually there. [1][7][9]
Find the actual cause
Inspect the error and component stack, the HTML response in Network and the DOM before hydration. The HTML parser may close a p before a div or insert tbody in a table; comparing JSX alone misses this. Nested buttons are invalid. Date.now(), Math.random(), a typeof window branch in render and differing inputs can produce different trees. Reproduce with a clean browser profile; extensions and CDN HTML transformations can also alter the result. [2][3][10][12]
One data and time snapshot
src/snapshot.ts
export interface Snapshot {
generatedAt: string;
label: string;
}
function isObject(value: unknown): value is object {
if (value === null) {
return false;
}
return typeof value === "object";
}
function isCanonicalInstant(value: unknown): value is string {
if (typeof value !== "string") {
return false;
}
const milliseconds = Date.parse(value);
if (!Number.isFinite(milliseconds)) {
return false;
}
return new Date(milliseconds).toISOString() === value;
}
function isNonEmptyText(value: unknown): value is string {
if (typeof value !== "string") {
return false;
}
return value.trim().length > 0;
}
export function parseSnapshot(raw: string): Snapshot {
const value: unknown = JSON.parse(raw);
if (!isObject(value)) {
throw new TypeError("Expected a snapshot object.");
}
if (!("generatedAt" in value)) {
throw new TypeError("Missing timestamp.");
}
if (!("label" in value)) {
throw new TypeError("Missing label.");
}
if (!isCanonicalInstant(value.generatedAt)) {
throw new TypeError("Invalid timestamp.");
}
if (!isNonEmptyText(value.label)) {
throw new TypeError("Invalid label.");
}
return {
generatedAt: value.generatedAt,
label: value.label,
};
}
export function createSnapshot(now: Date): Snapshot {
const generatedAt = now.toISOString();
const formatter = new Intl.DateTimeFormat("en-GB", {
dateStyle: "medium",
timeStyle: "short",
timeZone: "UTC",
});
return {
generatedAt,
label: `${formatter.format(now)} UTC`,
};
}
export function serializeSnapshot(snapshot: Snapshot): string {
return JSON.stringify(snapshot).replaceAll("<", "\\u003c");
}
Related reading: JavaScript Date, Intl and Temporal.
Do not calculate the generation time, product count or random ID independently on the server and client. Create a public snapshot per request and pass the exact same data to both renders. Explicit UTC and locale reduce differences, but ICU versions may still format text differently; the lab transfers the already formatted label. Its parser accepts canonical toISOString output, rejecting empty labels and invalid dates. It is not a general ISO 8601 validator. [1][15]
Safe SSR state transport
src/server.tsx
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { renderToString } from "react-dom/server";
import { App } from "./app";
import { createSnapshot, serializeSnapshot } from "./snapshot";
const PORT = 4173;
function renderPage(): string {
const snapshot = createSnapshot(new Date());
const markup = renderToString(<App snapshot={snapshot} />);
const data = serializeSnapshot(snapshot);
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hydration lab</title>
<link rel="stylesheet" href="/en/styles.css">
</head>
<body>
<div id="root">${markup}</div>
<script id="initial-data" type="application/json">${data}</script>
<script type="module" src="/client.js"></script>
</body>
</html>`;
}
const assets = new Map<string, readonly [string, string]>([
["/client.js", ["dist/client.js", "text/javascript"]],
["/styles.css", ["src/styles.css", "text/css"]],
]);
createServer(async (request, response) => {
try {
if (request.method !== "GET") {
response.writeHead(405, { Allow: "GET" }).end();
return;
}
const path = request.url ?? "/";
if (path === "/") {
const html = renderPage();
response.writeHead(200, {
"Content-Type": "text/html; charset=utf-8",
"Cache-Control": "no-store",
});
response.end(html);
return;
}
const asset = assets.get(path);
if (!asset) {
response.writeHead(404).end();
return;
}
const [filename, type] = asset;
const content = await readFile(filename);
response.writeHead(200, { "Content-Type": type });
response.end(content);
} catch (error) {
console.error(error);
if (response.headersSent) {
response.destroy();
return;
}
response.writeHead(500).end("Internal error");
}
}).listen(PORT, "127.0.0.1");
src/client.tsx
import { hydrateRoot } from "react-dom/client";
import { App } from "./app";
import { parseSnapshot } from "./snapshot";
const root = document.getElementById("root");
const data = document.getElementById("initial-data");
if (!(root instanceof HTMLElement)) {
throw new Error("Missing application root.");
}
if (!(data instanceof HTMLScriptElement)) {
throw new Error("Missing initial snapshot.");
}
const snapshot = parseSnapshot(data.textContent ?? "");
hydrateRoot(root, <App snapshot={snapshot} />, {
onRecoverableError(error, info) {
console.error("Recoverable React error", error, info.componentStack);
},
});
The lab uses renderToString for a small page without Suspense suspension. It embeds data in an application/json script; the client reads textContent, validates the shape and only then hydrates. Escaping the less-than character as a Unicode sequence prevents data from terminating the script element; JSON.stringify alone is insufficient in this context. Never expose secrets in HTML. Prefer framework serialization and streaming in production. Report recoverable errors without private payloads. [1][9][10][14]
Browser state and useSyncExternalStore
src/use-dark-preference.ts
import { useSyncExternalStore } from "react";
const QUERY = "(prefers-color-scheme: dark)";
function subscribe(notify: () => void): () => void {
const media = window.matchMedia(QUERY);
media.addEventListener("change", notify);
return () => {
media.removeEventListener("change", notify);
};
}
function getSnapshot(): boolean {
return window.matchMedia(QUERY).matches;
}
function getServerSnapshot(): null {
return null;
}
export function useDarkPreference(): boolean | null {
return useSyncExternalStore<boolean | null>(
subscribe,
getSnapshot,
getServerSnapshot,
);
}
Do not read matchMedia or localStorage during ordinary server rendering. The custom hook supplies null both during SSR and hydration, then reads the actual preference. The stable subscription removes its listener on unsubscribe. An object snapshot must retain identity until data changes. Alternatively read browser state in useEffect after hydration, accounting for the extra render, possible flicker and localStorage failures. For visual theming alone, CSS prefers-color-scheme is often enough. [5][6]
Identifiers, state and semantics
src/app.tsx
import { useId, useState } from "react";
import type { Snapshot } from "./snapshot";
import { useDarkPreference } from "./use-dark-preference";
interface AppProps {
snapshot: Snapshot;
}
function describePreference(value: boolean | null): string {
if (value === null) {
return "Checking browser preference";
}
return value ? "Dark preference" : "Light preference";
}
export function App({ snapshot }: AppProps) {
const inputId = useId();
const darkPreference = useDarkPreference();
const [count, setCount] = useState(0);
function increment(): void {
setCount((previous) => previous + 1);
}
return (
<main>
<h1>Hydration lab</h1>
<p>
Generated: {" "}
<time dateTime={snapshot.generatedAt}>{snapshot.label}</time>
</p>
<p>{describePreference(darkPreference)}</p>
<label htmlFor={inputId}>Note</label>
<input id={inputId} name="note" />
<button type="button" onClick={increment}>
Increment
</button>
<p role="status">Count: {count}</p>
</main>
);
}
src/styles.css
:root {
color-scheme: light dark;
font-family: system-ui, sans-serif;
}
main {
max-width: 40rem;
margin: 4rem auto;
padding: 1rem;
display: grid;
gap: 1rem;
}
input,
button {
font: inherit;
padding: 0.75rem;
}
:focus-visible {
outline: 3px solid Highlight;
outline-offset: 3px;
}
Related reading: React Rendering and Reconciliation.
useId associates a label and input when the SSR and client trees agree. It is not for list keys or entity identifiers. With multiple independent roots, select distinct identifierPrefix values, matching server and client within each root. The lab shares App, initial count 0 and the formatted time label. Clicking the button updates the count; semantic elements make behavior testable without inspecting internal state. [4][1]
Next.js boundaries and escape hatches
next-example/app/page.tsx
import { createSnapshot } from "../src/snapshot";
import { ClientApp } from "./client-app";
export default function Page() {
const publishedAt = new Date("2026-11-27T10:00:00.000Z");
const snapshot = createSnapshot(publishedAt);
return <ClientApp snapshot={snapshot} />;
}
next-example/app/client-app.tsx
"use client";
import { App } from "../src/app";
import type { Snapshot } from "../src/snapshot";
interface ClientAppProps {
snapshot: Snapshot;
}
export function ClientApp({ snapshot }: ClientAppProps) {
return <App snapshot={snapshot} />;
}
Related reading: React Server Components vs Client Components.
The use client directive defines a client module boundary, not an automatic opt-out from HTML prerendering. Pass serializable data from a Server Component and match initial query-cache state. dynamic with ssr: false can isolate a DOM-dependent library inside a Client Component, at the cost of initial HTML. suppressHydrationWarning is a narrow, one-level escape hatch for unavoidable differences, not a recursive fix; React does not patch mismatched text this way. Do not suppress errors globally on html. [1][2][7][8][16]
Copy the Next.js variant into a separate App Router project as described in README. The fixed date represents a sample record, not the current request time. The framework transfers the snapshot to the Client Component; do not copy the custom hydrateRoot entry point. [1][2][7][8][16]
Regression tests with Given-When-Then
npm install
npm run typecheck
npm run test:unit
npm run build
npx playwright install chromium
npm run test:e2e
tests/snapshot.test.cjs
const { test } = require("node:test");
const assert = require("node:assert/strict");
const {
createSnapshot,
parseSnapshot,
serializeSnapshot,
} = require("../dist-unit/snapshot.js");
const instant = "2026-11-27T10:00:00.000Z";
const snapshot = { generatedAt: instant, label: "27 Nov 2026 UTC" };
test("Given a valid snapshot, serialization preserves the values", () => {
// Given
const raw = serializeSnapshot(snapshot);
// When
const result = parseSnapshot(raw);
// Then
assert.deepEqual(result, snapshot);
});
test("Given script-closing text, JSON cannot close the script", () => {
// Given
const value = { ...snapshot, label: "</script><script>alert(1)" };
// When
const raw = serializeSnapshot(value);
// Then
assert.equal(raw.includes("<"), false);
assert.deepEqual(parseSnapshot(raw), value);
});
const invalid = [
"null",
"[]",
"42",
"{}",
"{",
JSON.stringify({ ...snapshot, generatedAt: "2026-11-27" }),
JSON.stringify({ ...snapshot, generatedAt: "invalid" }),
JSON.stringify({ ...snapshot, generatedAt: "2026-02-30T00:00:00.000Z" }),
JSON.stringify({ ...snapshot, label: " " }),
JSON.stringify({ ...snapshot, label: 5 }),
];
for (const [index, raw] of invalid.entries()) {
test(`Given invalid snapshot ${index + 1}, parsing rejects it`, () => {
// When / Then
assert.throws(() => parseSnapshot(raw));
});
}
test("Given a fixed date, the initial label uses UTC", () => {
// Given
const now = new Date(instant);
// When
const result = createSnapshot(now);
// Then
assert.equal(result.generatedAt, instant);
assert.match(result.label, /UTC$/);
});
tests/hydration.spec.ts
import { expect, test } from "@playwright/test";
for (const timeZone of ["Europe/Warsaw", "America/New_York"]) {
test.describe(timeZone, () => {
test.use({ timezoneId: timeZone, colorScheme: "dark" });
test("initial HTML hydrates and remains interactive", async ({
page,
}) => {
// Given
const errors: string[] = [];
page.on("pageerror", (error) => errors.push(error.message));
page.on("console", (message) => {
if (message.type() === "error") {
errors.push(message.text());
}
});
// When
const response = await page.goto("/");
// Then
if (!response) {
throw new Error("Missing navigation response.");
}
expect(response.ok()).toBe(true);
const html = await response.text();
expect(html).toContain("Checking browser preference");
await expect(page.getByText("Dark preference")).toBeVisible();
const initialTime = html.match(/<time[^>]*>([^<]+)<\/time>/);
if (!initialTime) {
throw new Error("Missing server time label.");
}
const label = initialTime[1];
if (label === undefined) {
throw new Error("Missing server time text.");
}
await expect(page.locator("time")).toHaveText(label);
await page.getByLabel("Note").fill("Hydrated");
await page.getByRole("button", { name: "Increment" }).click();
await expect(page.getByRole("status")).toHaveText("Count: 1");
expect(errors).toEqual([]);
});
});
}
test("reports a deliberately changed client snapshot", async ({ page }) => {
// Given
const label = "Different client label";
const recoveryErrors: string[] = [];
page.on("console", (message) => {
if (message.text().startsWith("Recoverable React error")) {
recoveryErrors.push(message.text());
}
});
await page.route("**/", async (route) => {
const response = await route.fetch();
const original = await response.text();
const body = original.replace(
/"label":"[^"]*"/,
`"label":${JSON.stringify(label)}`,
);
expect(body).not.toBe(original);
await route.fulfill({ response, body });
});
// When
await page.goto("/");
// Then
await expect(page.locator("time")).toHaveText(label);
await expect.poll(() => recoveryErrors.length).toBeGreaterThan(0);
});
playwright.config.ts
import { defineConfig } from "@playwright/test";
export default defineConfig({
testDir: "./tests",
use: { baseURL: "http://127.0.0.1:4173" },
webServer: {
command: "npm run serve",
url: "http://127.0.0.1:4173",
reuseExistingServer: false,
},
});
Run the lab using README. Node.js tests cover snapshot contracts, malformed data and script termination protection. The Playwright test captures pageerror and console.error before navigation, compares the time label from the HTML response, checks the dark preference after hydration and exercises the form. Repeat in different zones, with slow JavaScript and a production build. Absence of errors is not sufficient: assert a successful user action. Parser tests alone cannot prove hydration correctness. [11][13]
The last test deliberately changes only the JSON label in the response while retaining server HTML. It expects a recovery event and the new label. This is a controlled regression, not production code. [11][13]
Production diagnosis and deployment
If the issue occurs only after deployment, check HTML, manifest and JavaScript version alignment, CDN rules, Service Workers and cache keys covering locale and personalization. Never serve private HTML from a shared cache. React 19 reports clearer mismatch details; in a self-managed root onRecoverableError captures recovery events, but not every warning goes through it. Collect release identifiers and sanitized context rather than a user's entire HTML. Fix the mismatch source and measure interactivity impact. [1][2][12]
