Next.js●

Next.js “Hydration failed because the initial UI does not match”: 7 Causes and How I Fix Each One

You hit refresh and the red overlay appears: Hydration failed because the initial UI does not match. No file, no line number. Here are the 7 causes I see most often in Next.js apps, how to find the mismatch fast, and which fixes are worth using.

Next.js hydration failed error illustration showing server and client UI mismatch, 7 common causes, and solutions.

You change nothing in the component, hit refresh, and the red overlay appears: Hydration failed because the initial UI does not match what was rendered on the server. No file name. No line number. Just a complaint that something, somewhere, is different.

Here is what’s happening. Next.js renders your components to HTML on the server. The browser shows that HTML, then React runs the same components again on the client and compares the result to the existing DOM. If the two trees differ, React complains. Every cause below is a version of “the server and the client computed different output from the same code.”

Finding the culprit first

On React 19 (Next.js 15), the dev overlay shows a diff with the mismatched element marked. Read it before you do anything else. On React 18 the message is vaguer, and you’ll be comparing “View Source” (what the server sent) against the Elements panel (what the client built). If neither helps, comment out half the page and bisect. It’s dull, but it works in about four rounds.

Also open the page in an incognito window with extensions off. You’ll see why in cause 5.

1. Dates and number formatting

This is the most common one I see in dashboards and blog templates.

jsx

<span>{new Date(post.createdAt).toLocaleString()}</span>

The server formats that date using its own timezone and locale. Your server is probably in UTC with an en-US default. The user’s browser might be UTC+5 with en-GB. Different strings, instant mismatch. Same problem with toLocaleString() on numbers and currencies.

Fix it by making the output deterministic. Pass an explicit locale and timeZone to Intl.DateTimeFormat, or send the ISO string and format it after mount. If the display really must be in the user’s local time, accept the two-step render and do it in useEffect. Showing a dash or a UTC date for one frame is better than an error.

2. Random values and ids in render

Math.random(), Date.now(), crypto.randomUUID() inside a component body. The server picks one value, the client picks another. Nothing more to it.

For form field ids and aria attributes, use useId. It produces matching ids on both sides. Don’t use it for list keys, though. For anything else that’s random, generate it in useEffect or on the server and pass it down as a prop.

3. Browser-only checks in the render path

jsx

const isMobile = typeof window !== 'undefined' && window.innerWidth < 768;
return isMobile ? <MobileNav /> : <DesktopNav />;

On the server window doesn’t exist, so you get DesktopNav. On a phone the client gets MobileNav. Boom. Reading localStorage in a useState initializer does the same thing.

The standard fix is a mounted flag:

const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!mounted) return <DesktopNav />;

It works, but it costs you a second render and often a layout jump. Two better options exist. For layout, use CSS media queries and render both components, hiding one with a class. Zero JavaScript, zero mismatch. For values that really live in the browser (matchMedia, localStorage, online status), use useSyncExternalStore with a getServerSnapshot function. That’s what the API is for, and almost nobody uses it.

My rule: if a width check decides layout, it belongs in CSS, not in React.

4. Invalid HTML nesting

This one confuses people because the bug isn’t in your React code at all. The browser’s HTML parser fixes broken markup before React ever looks at it. Put a <div> inside a <p> and the parser closes the paragraph early, so the DOM React finds is different from the tree it expected.

The usual offenders:

  • <div> or <ul> inside <p>
  • <a> inside <a> (often a <Link> wrapping an old-style <a> tag, since Link renders its own anchor now)
  • <button> inside <button>
  • Markdown or CMS rich text injected into a <p> with dangerouslySetInnerHTML

React will usually warn about invalid nesting in the console right next to the hydration error. If it doesn’t, validate the rendered HTML. The fix is just changing the wrapper element. Swap the <p> for a <div> and move on.

VS Code editor showing a React component with invalid HTML nesting, where a <div> element is placed inside a <p> tag, triggering a React validateDOMNesting warning.

5. Browser extensions

Grammarly, password managers, dark mode extensions and translation tools all modify the DOM before React hydrates. Google Translate wraps text nodes in extra elements. Some extensions inject attributes onto <body> or <html>. React sees attributes it never rendered and throws.

The tell: the error shows for you and not for your teammate, or it vanishes in incognito. If that’s the pattern, stop debugging your code. For extension noise on the root, put suppressHydrationWarning on <html> or <body> in your root layout. It’s a legitimate use.

6. Theme switchers and CSS-in-JS

Two separate problems that look the same.

Theme libraries like next-themes set a class or data-theme attribute on <html> with an inline script before hydration, to avoid a flash of the wrong theme. React then finds an attribute it didn’t render. The library’s docs tell you to add suppressHydrationWarning to the <html> tag, and that’s the correct fix. Don’t read the theme from localStorage in your own component and render it directly. That’s cause 3 again.

CSS-in-JS is the other one. styled-components and Emotion generate class names and inject style tags. In the App Router they need a registry component that collects styles during server rendering, otherwise server and client class names diverge. If you’re starting a new project, I’d skip runtime CSS-in-JS entirely and use CSS Modules or Tailwind. This category of bug disappears, and you don’t pay the runtime cost either.

7. Something between your server and the browser rewrites the HTML

Your code is fine, local dev is clean, and production throws the error. Check what the browser actually receives:

curl -s https://yoursite.com/page > edge.html

Compare it with the HTML from your own server or next start locally. Proxies and CDNs sometimes transform responses. Cloudflare’s email address obfuscation and Rocket Loader are the ones I’d check first, and any security or analytics layer that injects scripts or markup can do it too. If the HTML at the edge differs from what Next.js produced, the client will never match it. Turn off the rewriting feature for that route.

What I’d stop doing

Sprinkling suppressHydrationWarning everywhere. It only silences one level of text or attribute mismatch, it doesn’t fix anything, and it hides real bugs. Use it on <html>, <body>, and on a single timestamp element where you’ve deliberately accepted a difference. Nowhere else.

The other habit I’d drop is wrapping whole components in dynamic(() => import(...), { ssr: false }) the moment an error shows up. In the App Router that has to live in a Client Component, and it means that part of the page ships empty in the HTML. If it’s above the fold, you’ve traded a console error for a content flash and worse perceived load. Use it for things that genuinely can’t render on a server, like a chart library that touches window on import.

Next time you see the overlay: reproduce it in incognito first, read the diff, then grep the component for window, Date, Math.random, and localStorage. Those four searches find most of them.