DEV Community

Libme
Libme

Posted on

Next.js "Hydration Failed Because the Server Rendered HTML Didn't Match the Client": Find the Cause, Then Pick the Fix

Hydration errors mean the HTML your server produced differs from what React rendered on the client's first pass. The cause is almost always one of four things: a value that differs between server and browser (dates, locale, random IDs), browser-only APIs read during render, invalid HTML nesting, or a browser extension rewriting the DOM. Find which one it is before reaching for suppressHydrationWarning, because that flag hides the symptom without fixing anything.

What does the error actually say?

Depending on your React and Next.js version (as of late 2026, React 19 with a recent Next.js), you will see one of these in the console:

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

Warning: Text content did not match. Server: "11/25/2026" Client: "25/11/2026"

Warning: Expected server HTML to contain a matching <div> in <p>.
Enter fullscreen mode Exit fullscreen mode

Newer versions print a diff with + and - lines showing what the client expected versus what the server sent. Read that diff first. It usually points at the exact element, and the element tells you which of the four causes you have.

The cost of ignoring it is real: React discards the server HTML for that tree and re-renders on the client, so you pay for SSR and lose its benefit, and the UI may flicker.

Takeaway: the diff in the console names the mismatching node, and that node tells you the cause.

Which cause do you have?

Symptom in the diff Likely cause Right fix
Text differs by date, time, or number format toLocaleString() / new Date() with different timezone or locale on server vs browser Render a stable value, format after mount
Text or id/key differs randomly each load Math.random(), Date.now(), crypto.randomUUID() in render useId() or generate inside an effect
Content only exists in the browser window, localStorage, matchMedia read during render useSyncExternalStore or an effect
"Expected server HTML to contain a matching <div> in <p>" Invalid nesting such as <div> inside <p>, <a> inside <a> Fix the markup
Extra attributes or nodes you did not write Browser extension (translators, dark-mode tools, password managers) Test in a clean profile; usually ignore

Takeaway: four causes cover nearly every hydration error, and each has a different correct fix.

How do I fix dates and locale mismatches?

The server runs in UTC (on most hosts) with its own default locale. The browser uses the user's timezone and language. Any new Date().toLocaleString() in render will differ.

This breaks:

export function PostedAt({ iso }: { iso: string }) {
  return <time>{new Date(iso).toLocaleString()}</time>;
}
Enter fullscreen mode Exit fullscreen mode

Two options. If the exact local format does not matter at first paint, pin it so both sides agree:

export function PostedAt({ iso }: { iso: string }) {
  const text = new Intl.DateTimeFormat("en-US", {
    dateStyle: "medium",
    timeStyle: "short",
    timeZone: "UTC",
  }).format(new Date(iso));
  return <time dateTime={iso}>{text} UTC</time>;
}
Enter fullscreen mode Exit fullscreen mode

If you want the viewer's local time, render the stable version first and upgrade after hydration:

"use client";
import { useEffect, useState } from "react";

export function LocalTime({ iso }: { iso: string }) {
  const [text, setText] = useState(() =>
    new Date(iso).toISOString().slice(0, 16).replace("T", " ") + " UTC"
  );
  useEffect(() => {
    setText(new Date(iso).toLocaleString());
  }, [iso]);
  return <time dateTime={iso}>{text}</time>;
}
Enter fullscreen mode Exit fullscreen mode

The first client render matches the server, then the effect swaps in the local string. The drawback is a brief visible swap, which is the honest price of showing a per-user value in server-rendered HTML.

Takeaway: either make both sides format identically (pin timezone and locale) or render a stable value and localize in an effect.

How do I handle random IDs and browser-only values?

For IDs that link labels to inputs, do not invent them yourself. React's useId() produces values that are stable across server and client:

import { useId } from "react";

export function Field({ label }: { label: string }) {
  const id = useId();
  return (
    <>
      <label htmlFor={id}>{label}</label>
      <input id={id} />
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

For values that only exist in the browser, such as localStorage or a media query, the common mistake is reading them directly during render with a typeof window !== "undefined" check. That check makes server and client output differ by design, which is exactly the bug. Use useSyncExternalStore, which takes a separate server snapshot:

"use client";
import { useSyncExternalStore } from "react";

function subscribe(cb: () => void) {
  const mq = window.matchMedia("(prefers-color-scheme: dark)");
  mq.addEventListener("change", cb);
  return () => mq.removeEventListener("change", cb);
}

export function useIsDark() {
  return useSyncExternalStore(
    subscribe,
    () => window.matchMedia("(prefers-color-scheme: dark)").matches,
    () => false // what the server (and first hydration pass) assumes
  );
}
Enter fullscreen mode Exit fullscreen mode

React uses the server snapshot during hydration and then re-renders with the real value if it differs, with no mismatch warning.

A heavier alternative is next/dynamic with ssr: false for a component that cannot render on the server at all (a chart library touching window at import time, say). It works, but that component ships no server HTML, so you lose its content for crawlers and first paint. Use it for widgets, not for content you want indexed.

Takeaway: give React a separate server snapshot instead of branching on typeof window during render.

Why does invalid HTML nesting cause hydration errors?

Browsers repair invalid markup while parsing. If your component renders <p><div>...</div></p>, the HTML parser closes the <p> early, so the DOM the browser builds no longer matches the tree React expects. The server output looked fine in your JSX, but the parsed result is different.

Common offenders: a <div> or <ul> inside <p>, a <a> inside another <a>, a <tr> without <tbody> context, or a markdown renderer that wraps block components in a paragraph. The fix is to change the markup, for example use <span> or swap the outer <p> for a <div>. No hydration trick helps here.

Takeaway: if the error mentions an element "in" another element, fix the nesting; no React API can paper over it.

When is suppressHydrationWarning acceptable?

It is a one-level escape hatch for content that is expected to differ and is a single text node or attribute, such as a clock or the <html> tag when a theme script sets a class before hydration:

<html lang="en" suppressHydrationWarning>
Enter fullscreen mode Exit fullscreen mode

It does not patch up mismatched structure, and it only applies one level deep. Treat it as a deliberate declaration ("this differs on purpose"), not a way to silence errors you have not diagnosed.

Takeaway: use suppressHydrationWarning only for values that are meant to differ, never for unexplained errors.

Is it a browser extension?

Before debugging your code for an hour, open the page in a private window with extensions disabled, or a fresh browser profile. Translators, dark-mode injectors, and some password managers add attributes or wrap text nodes, producing mismatches that exist only on your machine. If the error vanishes in a clean profile, your app is fine.

FAQ

Why does the hydration error only happen in production or only on refresh?
Production often runs the server in a different timezone and locale than your laptop, and caches rendered HTML, so date and locale mismatches appear only there. Also check whether a value is read from cookies or localStorage that differs between first and later visits.

Does a hydration error break my Next.js app?
React recovers by discarding the server HTML for the affected tree and rendering it on the client, so the page usually works but you lose SSR benefits for it and may see flicker. Treat it as a real bug, not cosmetic noise.

Can I just use useEffect to fix every hydration mismatch?
Only for value mismatches such as dates or browser-only data. It cannot fix invalid HTML nesting, which must be corrected in the markup.

Bottom line

Read the diff, classify the mismatch, and apply the matching fix: stable formatting or an effect for dates, useId for IDs, useSyncExternalStore for browser state, corrected markup for nesting. Keep suppressHydrationWarning for values that are meant to differ. If you keep hitting these across a large codebase, a lint rule banning Date.now() and Math.random() in render is cheaper than debugging each one.

Related reading

Top comments (0)