Next.js Hydration Mismatch: Why Server HTML Does Not Match the Client
React never reconciles a hydration mismatch; it re-renders the boundary. The four causes, the diff that finds them, and the patterns that keep the first client render identical to the server's.

Introduction & Quick Summary
Symptom. Hydration failed because the server rendered HTML didn't match the client. React 19 also reports it as Hydration failed because the server rendered text didn't match the client, as a minified code (#418, #423, #425), and through onRecoverableError with a diff. Next.js 16 shows it in the dev overlay pointing at the offending element; in production it only logs to the console and silently re-renders the mismatched subtree on the client.
Cause. The first client render produced different markup from the server render for the same element. React does not reconcile the difference — it discards the server HTML for that boundary and re-renders it. Four groups cover it: non-deterministic values (Date.now(), Math.random(), crypto.randomUUID(), toLocaleString() in another zone), environment checks that change output (typeof window, localStorage, matchMedia), invalid HTML nesting that the browser repairs before React sees it (<div> inside <p>, <tr> outside <tbody>, nested <a>), and DOM mutation by a third-party script or extension between parse and hydration.
Fix. Make the first client render identical to the server render: defer environment-dependent output to useEffect, or read it through useSyncExternalStore with an explicit server snapshot. Fix the nesting. Put suppressHydrationWarning only on leaf text whose difference is irrelevant. dynamic = 'force-dynamic', ssr: false, and remounting the tree do not fix a mismatch — they move it or hide the symptom.
Core Mechanics, Signatures & Reproducible Setup
Next.js produces HTML on the server plus an RSC payload carrying the component tree. On the client React builds a virtual tree and hydrates: it attaches listeners and adopts existing DOM nodes. Adoption requires structural agreement — if the client's node at a position is not the node type the server emitted there, React reports a mismatch and switches that Suspense boundary to client rendering. A mismatch inside a boundary that has not resolved yet produces the harsher Hydration failed because the initial UI does not match what was rendered on the server, which is why a component sometimes never appears until a later client update.
Reproduce it:
npx create-next-app@latest hydro-repro --ts --app --no-tailwind --no-eslint// app/page.tsx
export default function Page() {
const now = new Date();
return (
<main>
<p>Rendered at {now.toLocaleTimeString()}</p>
<p>Session {Math.random().toString(36).slice(2)}</p>
<button onClick={() => alert('hi')}>Ping</button>
</main>
);
}Both values disagree: the server formatted the time in the container's locale and zone, the browser in the user's, and Math.random() cannot agree at all. The button still works because React re-rendered that boundary — which is the trap: a small mismatch costs a full client render of the surrounding tree, losing focus and pending input.
Locate the divergence instead of guessing: the server HTML is a curl, the client's first render is Elements → right-click <html> → Copy outerHTML at load. Split both into one line per element and diff them; the first divergent line names the element and its position.
Key Comparison Table
| Approach | Guarantees | Cost | Use when |
|---|---|---|---|
| Deterministic render | Client output equals server output | None | Default |
useEffect + mounted flag | Client-only content after hydration | Extra render, empty first paint | Small widgets, charts |
useSyncExternalStore | Explicit server snapshot, no flash | A little more code | matchMedia, localStorage, navigator |
suppressHydrationWarning | React skips this element's warning | Text may differ visibly | Intentionally different leaf text |
dynamic(…, { ssr: false }) | Never renders on the server | Slower first paint | Canvas, maps, editors |
| Source | Message | First fix |
|---|---|---|
toLocaleString() / default Intl zone | text did not match | Pass timeZone, or format on the server |
Math.random() / uuid() in render | HTML did not match | Server value as prop, or useEffect |
window / localStorage guard | HTML did not match | useSyncExternalStore |
<div> in <p>, <tr> without <tbody> | HTML did not match (node type) | Fix the JSX nesting |
| Extension rewriting text | text did not match, some profiles only | suppressHydrationWarning on the leaf |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Relative timestamps and locale formatting
// Broken: two environments, two answers
<span>{new Date(post.publishedAt).toLocaleDateString()}</span>// Fixed A — format on the server with an explicit zone
const fmt = new Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeZone: 'UTC' });
<span>{fmt.format(new Date(post.publishedAt))}</span>// Fixed B — absolute time in HTML, relative time after mount
'use client';
export function RelativeTime({ iso }: { iso: string }) {
const [label, setLabel] = useState('');
useEffect(() => {
const update = () => {
const m = Math.round((Date.now() - new Date(iso).getTime()) / 60000);
setLabel(m < 60 ? `${m}m ago` : `${Math.round(m / 60)}h ago`);
};
update();
const id = setInterval(update, 60000);
return () => clearInterval(id);
}, [iso]);
return <time dateTime={iso} suppressHydrationWarning>{label}</time>;
}Intl without timeZone uses the runtime's zone: the container's at build, the browser's at view. toLocaleDateString() with no options is also locale-dependent, and containers commonly run with LANG=C.
2. Random values and IDs
// Broken: a new id on every render, on both sides
<div id={`field-${Math.random()}`}>
// Fixed: deterministic, identical on both sides
'use client';
import { useId } from 'react';
const id = useId(); // «r1» in React 19
<input id={id} aria-describedby={`${id}-hint`} />useId values are legal in id and aria-* but not as key, a database value, or a CSS selector («» are not selector-safe). Use real data for keys — an array index that can reorder reintroduces the same inconsistency at the list level.
3. Media queries, theme, and storage read during render
// Broken: the server has no window
const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
// Fixed: one store with an explicit server snapshot
function usePrefersDark() {
return useSyncExternalStore(
(cb) => {
const mql = window.matchMedia('(prefers-color-scheme: dark)');
mql.addEventListener('change', cb);
return () => mql.removeEventListener('change', cb);
},
() => window.matchMedia('(prefers-color-scheme: dark)').matches,
() => false, // server snapshot
);
}The server snapshot is what makes it correct: React renders false twice, then switches after hydration with no mismatch. The same shape works for localStorage (wrap reads in try/catch — Safari private mode throws), navigator.onLine, and viewport width. A mounted flag works for one widget but adds a render and an empty first paint.
4. Invalid HTML that the browser silently repairs
// Broken: <p> cannot contain a block element
<p>Read the <a href="/docs"><div className="badge">new</div>docs</a></p>The parser closes the <p> before the <div>, so the server tree has the <div> as a sibling while React's client tree keeps it as a child. The error points at an element that looks correct in your source — the classic "the bug is not where the message is". The same happens with <table><tr> without <tbody>, <button> inside <button>, and nested <form>. Validate the built HTML, not the JSX, because the repair only exists in the output:
npx html-validate "out/**/*.html" 2>/dev/null | head -305. Third-party scripts and extensions
If the mismatch appears only on some machines, suspect extensions (Grammarly, translators, ad blockers) and loaders that inject nodes. Confirm with a clean profile (npx playwright open --browser=chromium), then fix what you control: load scripts with next/script strategy="afterInteractive" so they do not touch the subtree React owns before hydration. For a value you cannot control — a translated label, a year written by an analytics tag — mark the leaf:
<footer suppressHydrationWarning>{legalText}</footer>suppressHydrationWarning is one level deep and does not help with a structural difference; a mismatched element type below it still throws.
Common Compilation/Runtime Mistakes & Version Gotchas
| Mistake | Why it fails | Correct approach |
|---|---|---|
dynamic(…, { ssr: false }) on the whole page | Ships an empty page, keeps the bug | Find the differing value |
useState(() => Date.now()) for a clock | The initializer runs on the server | useEffect plus suppressHydrationWarning |
Intl without timeZone | Container and browser zones differ | Explicit zone |
key={Math.random()} to force a remount | New key every render, remount loop | Stable key from data |
suppressHydrationWarning on a parent | Only one level deep | Apply to the leaf |
typeof window !== 'undefined' in render | Different output per environment | useSyncExternalStore |
Version notes: React 19 collapsed the React 18 messages (Text content does not match server-rendered HTML) into a smaller set and routes them through onRecoverableError, so monitoring rules that filter on the old strings miss them. Next.js 16 removed synchronous params, searchParams, cookies(), headers(), and draftMode(); a synchronous read that survives in a compatibility path can render a different value during streaming and surface as a hydration mismatch for the surrounding tree. Turbopack is the default build in 16, but its HTML output matches Webpack's for the same tree — a mismatch introduced by the upgrade is a component problem.
When the two trees are large, dump each to JSON and compare them with the JSON formatter or line-diff the fragments with the text diff tool; for a timestamp mismatch, confirm the offset with the timestamp converter before hardcoding a timeZone string, because an invalid zone fails at build time while a wrong one fails silently at runtime.
Try matching browser tools
All toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesNext.js 16 Upgrade: Async Params, proxy.ts, and Turbopack Build Breaks
The codemod gets you most of the way; the rest is async request APIs, a webpack config Turbopack refuses, and a renamed middleware file that silently stops running.
Next.js Static Export, Standalone Output, and Docker Deployment
Export has no server, standalone has a pruned one, and the default expects a full install. The three COPY lines that decide whether a container renders CSS.
Next.js Parallel Routes and Intercepting Routes: Slot Layouts and Modals
Named slots render several pages in one layout, and (.) interception makes a click open over the page while a direct link renders the full route. Why every slot needs default.tsx.
Next.js ISR: Route Revalidate, revalidateTag, and On-Demand Invalidation
Two clocks and one trigger: route revalidate seconds, fetch-level tags, and a webhook that calls revalidateTag. A timer is a ceiling on freshness, never a guarantee.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.