Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readNext.js
#Next.js#React#Hydration#Debugging
3D illustration of server HTML slabs and client component blocks diverging at a hydration seam with neon cyan and amber accents

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:

bash
npx create-next-app@latest hydro-repro --ts --app --no-tailwind --no-eslint
tsx
// 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

ApproachGuaranteesCostUse when
Deterministic renderClient output equals server outputNoneDefault
useEffect + mounted flagClient-only content after hydrationExtra render, empty first paintSmall widgets, charts
useSyncExternalStoreExplicit server snapshot, no flashA little more codematchMedia, localStorage, navigator
suppressHydrationWarningReact skips this element's warningText may differ visiblyIntentionally different leaf text
dynamic(…, { ssr: false })Never renders on the serverSlower first paintCanvas, maps, editors
SourceMessageFirst fix
toLocaleString() / default Intl zonetext did not matchPass timeZone, or format on the server
Math.random() / uuid() in renderHTML did not matchServer value as prop, or useEffect
window / localStorage guardHTML did not matchuseSyncExternalStore
<div> in <p>, <tr> without <tbody>HTML did not match (node type)Fix the JSX nesting
Extension rewriting texttext did not match, some profiles onlysuppressHydrationWarning on the leaf

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Relative timestamps and locale formatting

tsx
// Broken: two environments, two answers <span>{new Date(post.publishedAt).toLocaleDateString()}</span>
tsx
// 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>
tsx
// 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

tsx
// 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

tsx
// 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

tsx
// 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:

bash
npx html-validate "out/**/*.html" 2>/dev/null | head -30

5. 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:

tsx
<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

MistakeWhy it failsCorrect approach
dynamic(…, { ssr: false }) on the whole pageShips an empty page, keeps the bugFind the differing value
useState(() => Date.now()) for a clockThe initializer runs on the serveruseEffect plus suppressHydrationWarning
Intl without timeZoneContainer and browser zones differExplicit zone
key={Math.random()} to force a remountNew key every render, remount loopStable key from data
suppressHydrationWarning on a parentOnly one level deepApply to the leaf
typeof window !== 'undefined' in renderDifferent output per environmentuseSyncExternalStore

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 tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.