All articles
Next.jsReactSSRHydration

Fixing Hydration Mismatch Errors in Next.js

Why Next.js throws hydration mismatch errors (dates, window, invalid HTML, extensions, themes, locales) and the exact fix for each cause.

Tushar Pachouri12 min read

Hydration errors are some of the most common errors in Next.js, and some of the most confusing, because the code that causes them usually looks fine. The page renders, then React complains that the server and the browser disagree. This post covers every cause I keep running into, with broken and fixed code for each, and a routine for finding the culprit quickly.

TL;DR

  • Hydration fails when the first client render produces different HTML than the server did. Anything that depends on time, randomness, the browser, or the user's locale is a suspect.
  • Read browser-only values (window, localStorage, matchMedia) after hydration, using useEffect, useSyncExternalStore with a server snapshot, or next/dynamic with ssr: false.
  • Fix invalid HTML nesting (<div> in <p>, <a> in <a>, <tr> without <tbody>). The browser rewrites it before React sees it.
  • suppressHydrationWarning is an escape hatch for one element's own text and attributes. Use it for <html>/<body> attribute changes and timestamps, not to silence real bugs.
  • On React 19 (Next.js 15+), the error includes a diff. Read it before changing any code.

What hydration actually is

With server-side rendering, Next.js renders your components to HTML on the server and sends it to the browser, so content appears before any JavaScript runs. Then React loads in the browser and hydrates that HTML. It renders the same component tree again and attaches event handlers to the existing DOM nodes instead of creating new ones.

For that to work, the first client render must produce exactly what the server produced. If it doesn't, React can't safely reuse the DOM. In React 18 and 19 it throws away the mismatched part and re-renders it on the client. You get a flash of changed content, wasted work, and an error in the console.

React reuses the server HTML only when its first client render produces the same output.

This applies to both routers. In the App Router, Server Components never hydrate, but Client Components ("use client") are still server-rendered and then hydrated, so they can mismatch. In the Pages Router, every page component hydrates.

The symptom

On React 18 (Next.js 13/14 with the Pages Router, or older setups) you'll see some combination of these:

Text
Error: Text content does not match server-rendered HTML.
Error: Hydration failed because the initial UI does not match what was rendered on the server.
Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.
Warning: Expected server HTML to contain a matching <div> in <p>.
Warning: Prop `className` did not match. Server: "light" Client: "dark"

React 19 (Next.js 15 and later) merges these into one message with a diff:

Text
Hydration failed because the server rendered HTML didn't match the client.
As a result this tree will be regenerated on the client.

  <PostMeta publishedAt="2025-03-17T23:30:00Z">
    <p>
+     Published 18/3/2025, 5:00:00 am
-     Published 3/17/2025, 11:30:00 PM

Lines with + are what the client rendered, and lines with - are what came from the server. For attribute-only differences, React 19 logs a warning that starts with "A tree hydrated but some attributes of the server rendered HTML didn't match the client properties", and it doesn't patch them up.

Cause 1: dates, times and random values

The server runs in one time zone and locale (often UTC on a host), and the browser runs in the user's. toLocaleString() with no arguments uses whichever environment it runs in.

TSX
// Broken: server and browser format differently
export function PostMeta({ publishedAt }: { publishedAt: string }) {
  return <p>Published {new Date(publishedAt).toLocaleString()}</p>;
}

Fix it by making the output deterministic with an explicit locale and time zone:

TSX
// Fixed: same output everywhere
const formatter = new Intl.DateTimeFormat("en-US", {
  dateStyle: "medium",
  timeStyle: "short",
  timeZone: "UTC",
});

export function PostMeta({ publishedAt }: { publishedAt: string }) {
  return (
    <p>
      Published <time dateTime={publishedAt}>{formatter.format(new Date(publishedAt))} UTC</time>
    </p>
  );
}

If you really want the reader's local time, render a stable value first and switch after hydration:

TSX
"use client";

import { useEffect, useState } from "react";

export function LocalTime({ iso }: { iso: string }) {
  // Stable on server and first client render: "2025-03-17 23:30 UTC"
  const [text, setText] = useState(() => `${iso.slice(0, 16).replace("T", " ")} UTC`);

  useEffect(() => {
    setText(new Date(iso).toLocaleString());
  }, [iso]);

  return <time dateTime={iso}>{text}</time>;
}

The same rule applies to Date.now() ("posted 3 minutes ago") and Math.random(). Both give a different value on each render. For relative times, compute the value once on the server and pass it down as a prop, or update it in an effect. For random IDs used in id/htmlFor/aria-*, use useId, which React keeps stable between server and client:

TSX
"use client";

import { useId } from "react";

export function EmailField() {
  // Broken: const id = `email-${Math.random().toString(36).slice(2)}`;
  const id = useId();
  return (
    <>
      <label htmlFor={id}>Email</label>
      <input id={id} type="email" name="email" />
    </>
  );
}

Cause 2: reading browser APIs during render

This is the classic one. window, localStorage, sessionStorage, navigator and matchMedia don't exist on the server, so people guard them with typeof window. That stops the crash, but now the server and client render different things:

TSX
"use client";

// Broken: server renders "Welcome", client renders "Welcome back, Asha"
export function Greeting() {
  const name = typeof window !== "undefined" ? localStorage.getItem("name") : null;
  return <h2>{name ? `Welcome back, ${name}` : "Welcome"}</h2>;
}

Fix A: read it in an effect

Effects only run in the browser, after hydration. Render the server-safe value first, then update:

SERVER RENDER HYDRATION AFTER THE EFFECT name = null name = null name = "Asha" Welcome Welcome Welcome back, Asha sent as HTML matches, DOM reused normal state update on the server first render in the browser useEffect reads localStorage
Fix A keeps the first client render identical to the server, then updates in an effect.
TSX
"use client";

import { useEffect, useState } from "react";

export function Greeting() {
  const [name, setName] = useState<string | null>(null);

  useEffect(() => {
    setName(localStorage.getItem("name"));
  }, []);

  return <h2>{name ? `Welcome back, ${name}` : "Welcome"}</h2>;
}

Fix B: useSyncExternalStore with a server snapshot

For values that can change, like media queries, useSyncExternalStore is a better fit. React uses getServerSnapshot on the server and during hydration, then switches to the real value right after, with no mismatch:

TSX
"use client";

import { useSyncExternalStore } from "react";

const QUERY = "(prefers-reduced-motion: reduce)";

function subscribe(callback: () => void) {
  const mql = window.matchMedia(QUERY);
  mql.addEventListener("change", callback);
  return () => mql.removeEventListener("change", callback);
}

export function usePrefersReducedMotion() {
  return useSyncExternalStore(
    subscribe,
    () => window.matchMedia(QUERY).matches, // client snapshot
    () => false // server snapshot, also used during hydration
  );
}

Fix C: skip SSR for the component

If a component only makes sense in the browser (maps, canvas or WebGL scenes, editors), don't server-render it:

TSX
"use client";

import dynamic from "next/dynamic";

const MapView = dynamic(() => import("./MapView"), {
  ssr: false,
  loading: () => <div style={{ height: 320 }} aria-hidden="true" />,
});

export function LocationSection() {
  return <MapView />;
}

Note: In the App Router on Next.js 15+, ssr: false isn't allowed in a Server Component and fails the build. Call dynamic() inside a Client Component, as above. The Pages Router has no such restriction.

Cause 3: conditional rendering on typeof window

The same bug in a different shape. Conditionally rendering a whole element changes the tree structure, not just text:

TSX
// Broken: the button exists only on the client
{typeof window !== "undefined" && "share" in navigator && <ShareButton />}

A small hook makes "am I hydrated?" explicit and safe:

TSX
"use client";

import { useSyncExternalStore } from "react";

const subscribe = () => () => {};

export function useIsClient() {
  return useSyncExternalStore(
    subscribe,
    () => true, // client
    () => false // server and hydration
  );
}
TSX
"use client";

import { useIsClient } from "./useIsClient";
import { ShareButton } from "./ShareButton";

export function ShareSlot() {
  const isClient = useIsClient();
  const canShare = isClient && "share" in navigator;
  return canShare ? <ShareButton /> : null;
}

Cause 4: invalid HTML nesting

The server sends HTML as a string. The browser's HTML parser fixes invalid markup before React ever sees it, so the DOM no longer matches what React expects. These are the usual offenders:

The div start tag closes the open p, so the DOM no longer has the shape React rendered.
TSX
// Broken: <div> can't live inside <p>, so the parser closes the <p> early
<p className="intro">
  <div className="badge">New</div>
  Fresh post
</p>

// Fixed
<div className="intro">
  <span className="badge">New</span>
  Fresh post
</div>
TSX
// Broken: the parser inserts a <tbody> that React doesn't know about
<table>
  <tr>
    <td>Next.js</td>
  </tr>
</table>

// Fixed
<table>
  <tbody>
    <tr>
      <td>Next.js</td>
    </tr>
  </tbody>
</table>

Watch for this with Markdown/MDX renderers that wrap everything in <p>. A custom image component that renders a <figure> or <div> ends up inside a paragraph.

Nested links are common in clickable cards: a Link around the card, and another Link for a tag inside it. <a> inside <a> is invalid, and the parser splits them. Use one real link stretched over the card instead:

TSX
import Link from "next/link";

export function PostCard({ post }: { post: { slug: string; title: string; tag: string } }) {
  return (
    <article className="card">
      <h3>
        <Link href={`/blog/${post.slug}`} className="card-link">
          {post.title}
        </Link>
      </h3>
      <Link href={`/tags/${post.tag}`} className="tag">
        {post.tag}
      </Link>
    </article>
  );
}
CSS
.card {
  position: relative;
}
.card-link::after {
  content: "";
  position: absolute;
  inset: 0;
}
.tag {
  position: relative;
  z-index: 1;
}

Cause 5: browser extensions

Some extensions modify the DOM before React hydrates. Grammarly adds attributes like data-gr-ext-installed to <body>, ColorZilla adds cz-shortcut-listen, and password managers and translators inject their own. Your code is fine, but React sees attributes it didn't render.

First confirm it: open the page in a private window with extensions disabled. If the error disappears, it's an extension. Because the root elements are the usual target, put suppressHydrationWarning on them:

TSX
// app/layout.tsx
import type { ReactNode } from "react";

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en" suppressHydrationWarning>
      <body suppressHydrationWarning>{children}</body>
    </html>
  );
}

Warning: suppressHydrationWarning only works one level deep. It silences mismatches in that element's own attributes and direct text content, not its children. That's why it's safe on <html> and <body>: your actual content is still checked. Don't spread it around to hide mismatches you haven't understood.

Cause 6: themes and the dark-mode flicker

Theme state lives in localStorage or comes from prefers-color-scheme, and the server knows neither. Reading it during render causes a mismatch. Defaulting to light and switching in an effect causes a flash of the wrong theme.

The pattern next-themes uses solves both. A small blocking script sets the class on <html> before first paint, and suppressHydrationWarning on <html> allows that one attribute difference:

TSX
// app/providers.tsx
"use client";

import type { ReactNode } from "react";
import { ThemeProvider } from "next-themes";

export function Providers({ children }: { children: ReactNode }) {
  return (
    <ThemeProvider attribute="class" defaultTheme="system" enableSystem>
      {children}
    </ThemeProvider>
  );
}
TSX
// app/layout.tsx
import type { ReactNode } from "react";
import { Providers } from "./providers";

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en" suppressHydrationWarning>
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

Any component that renders differently based on the theme still has to wait for the client, because resolvedTheme is undefined on the server:

TSX
"use client";

import { useEffect, useState } from "react";
import { useTheme } from "next-themes";

export function ThemeToggle() {
  const [mounted, setMounted] = useState(false);
  const { resolvedTheme, setTheme } = useTheme();

  useEffect(() => setMounted(true), []);

  if (!mounted) {
    // Same size as the real button, so nothing shifts
    return <button type="button" className="theme-toggle" aria-label="Toggle theme" disabled />;
  }

  const isDark = resolvedTheme === "dark";
  return (
    <button
      type="button"
      className="theme-toggle"
      aria-label={isDark ? "Switch to light theme" : "Switch to dark theme"}
      onClick={() => setTheme(isDark ? "light" : "dark")}
    >
      {isDark ? "Light" : "Dark"}
    </button>
  );
}

Tip: Where you can, let CSS do it. Render both icons and hide one with .dark .icon-sun { display: none; }. The markup is identical on server and client, so there's nothing to mismatch and nothing to wait for.

Cause 7: locale-dependent number formatting

Numbers have the same problem as dates. (1234567.891).toLocaleString() prints 1,234,567.891 in en-US, 1.234.567,891 in de-DE and 12,34,567.891 in en-IN, depending on where the code runs.

TSX
// Broken: server locale vs browser locale
<span>{price.toLocaleString()}</span>

// Fixed: explicit locale and currency
const inr = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
<span>{inr.format(price)}</span>

If you need the visitor's locale, pick it once on the server and pass it down, so server and client format with the same value:

TSX
// app/pricing/page.tsx (Server Component)
import { headers } from "next/headers";
import { Price } from "./Price";

function pickLocale(acceptLanguage: string | null) {
  const candidate = (acceptLanguage ?? "").split(",")[0].split(";")[0].trim();
  try {
    return Intl.NumberFormat.supportedLocalesOf(candidate)[0] ?? "en-US";
  } catch {
    return "en-US"; // invalid tags like "*" throw a RangeError
  }
}

export default async function PricingPage() {
  const locale = pickLocale((await headers()).get("accept-language"));
  return <Price amount={1999.5} currency="USD" locale={locale} />;
}
TSX
// app/pricing/Price.tsx
"use client";

export function Price({ amount, currency, locale }: { amount: number; currency: string; locale: string }) {
  return <span>{new Intl.NumberFormat(locale, { style: "currency", currency }).format(amount)}</span>;
}

headers() is async in Next.js 15. On 14 it returns the value directly, and await on it still works.

How to find the culprit

  1. Read the full error. On React 19, the diff names the component and shows both values. On React 18 with Next.js 14, the dev overlay shows the component stack. Start at the deepest component you own.
  2. Compare server HTML with the live DOM. Use "View page source" (what the server sent) next to the Elements panel (what the browser built). Or disable JavaScript in DevTools and reload to see the pure server output.
  3. Rule out extensions with a private window.
  4. Binary search. Comment out half of the suspect component's children and reload. Repeat until the error goes away.
  5. Test with a different time zone and locale. In Chrome DevTools, the Sensors panel can override location, time zone and locale. Many date bugs only show up when your machine and the server disagree.

Checklist

  • No new Date(), Date.now(), Math.random() or toLocale*() without explicit options in rendered output.
  • No window, localStorage, navigator or matchMedia reads during render. Use effects, useSyncExternalStore, or ssr: false.
  • No typeof window checks that change what gets rendered.
  • Valid HTML: no block elements in <p>, no nested <a>, tables have <tbody>.
  • suppressHydrationWarning only on <html>/<body> or deliberate single elements like timestamps.
  • Theme-dependent UI waits for mount, or uses CSS instead.
  • Locale and time zone are chosen once and passed down, not inferred separately on each side.

Wrap-up

Every hydration error comes down to one thing: the server and the first client render saw different inputs. Once you think of it that way, the fix is usually obvious. Make the input the same on both sides (explicit locale, time zone, IDs from useId), or wait until after hydration to use the input that only the browser has. Use suppressHydrationWarning sparingly, and fix everything else at the source.

Stuck on something like this?

I build and fix full-stack products for startups and indie founders. Tell me what's broken.

Get in touch