Skip to main content
CodingMarble

Error fixes

Fix Next.js Hydration Failed: Server HTML Mismatch

This error means the HTML React rendered on the server is different from what React produced in the browser on its first render, so it cannot attach to the existing markup. Find the node that differs, make the first client render produce exactly what the server produced, and move anything browser-only or time-dependent into an effect that runs after mount.

By CodingMarble · Published · 5 min read

A padlock on a laptop with light trails
Photo: FlyD on Unsplash

The error text and what it means

Depending on your React and Next.js versions, the message is worded a little differently, but the meaning is the same. These are the strings people usually search for:

Prompt· Common wordings of the hydration error
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: "10:41:02" Client: "10:41:03"

Warning: Expected server HTML to contain a matching <div> in <p>.

Warning: validateDOMNesting(...): <div> cannot appear as a descendant of <p>.

With server rendering, the server turns your components into an HTML string and sends it. The browser shows that HTML immediately, then React downloads, runs your components again on the client and walks the existing DOM, attaching event handlers to nodes it expects to find. That attach step is hydration. React assumes the first client render produces the same tree as the server render. If a text node, attribute or element differs, React cannot trust the existing markup. In current versions it throws away the mismatched part and rebuilds it on the client, which costs performance and can cause a visible flicker. Older versions only logged a warning and left the DOM in an inconsistent state.

The key idea is that the check is about the first render only. Anything that changes after mount, through state set in an effect, is fine. The bug is always a render function whose output depends on something the server and the browser see differently.

Common causes, roughly by how often they appear

Values that change between two calls are the most frequent cause. Calling new Date(), Date.now() or Math.random() directly in the render body gives the server one value and the browser another. Generating ids with Math.random for form labels has the same problem; React's useId hook exists for that case.

Reading browser-only state in render is the second cause. Code such as typeof window !== 'undefined' ? localStorage.getItem('theme') : 'light' returns 'light' on the server and the stored value in the browser, so the first client render differs. The same goes for window.innerWidth, navigator.language, matchMedia and document.cookie reads used to choose what to render.

Locale and timezone formatting is the third. Calling toLocaleString() or Intl.DateTimeFormat without explicit options uses the runtime default. The server may run in UTC with one locale while the visitor's browser uses another, so the same timestamp prints as different text.

Invalid HTML nesting is the fourth, and it is easy to miss because it looks fine in your component code. A div inside a p, a p inside a p, a nested anchor tag, or a table with a tr placed directly inside table without tbody can be silently rewritten by the browser's HTML parser. The browser's corrected DOM no longer matches what React expected. Finally, browser extensions that inject nodes or attributes into the page, such as translation tools, password managers and dark-mode injectors, can trigger the error even when your code is correct. Test in a private window with extensions disabled before debugging further.

Find the exact mismatching node

Do not guess. Recent React versions print a diff in the console showing the server markup and the client markup with a marker where they diverge, and Next.js development overlay shows the component stack. Read the first differing line and the component name above it. Older versions report only the text, in which case search your project for that text or for the element named in the warning.

A second technique is to view the raw server response. Run curl against the page, or use view-source in the browser (not the Elements panel, which shows the live DOM after hydration), and compare the HTML for that region with what the page renders. If the two differ in a timestamp, a price format or a class name, you have found the culprit. If the region looks identical but the error persists, suspect invalid nesting or an extension.

To narrow down a large page, comment out sibling components until the error disappears, or render a suspect component only after a mount flag is set. Binary search works well here because the error appears on first load regardless of where in the tree the bad node sits.

Fixes for browser-only and time-dependent values

The general fix is to render a stable placeholder first and swap in the real value after mount. State set inside useEffect runs only in the browser and only after hydration finished, so the first render matches the server.

TSX· A mount flag keeps the first render identical on server and client
"use client";
import { useEffect, useState } from "react";

export function ThemeLabel() {
  const [theme, setTheme] = useState<string | null>(null);

  useEffect(() => {
    setTheme(localStorage.getItem("theme") ?? "light");
  }, []);

  // First render (server and client): placeholder. After mount: real value.
  return <span>{theme ?? "Loading theme"}</span>;
}

If a whole component only makes sense in the browser, such as a chart library that touches window on import, load it with next/dynamic and ssr set to false. This skips server rendering for that component entirely, so there is nothing to mismatch. Note that in the App Router the dynamic call with ssr false must live in a Client Component, and the server then sends only the fallback. The trade-off is that the content is absent from the initial HTML, which matters if search engines or first paint depend on it.

TSX· Skip server rendering for a browser-only component
"use client";
import dynamic from "next/dynamic";

const PriceChart = dynamic(() => import("./PriceChart"), {
  ssr: false,
  loading: () => <p>Loading chart</p>,
});

export function ChartSection() {
  return <PriceChart />;
}

For dates, make the output deterministic. Pass an explicit locale and an explicit timeZone to Intl.DateTimeFormat so the server and browser agree, or format on the server and pass a string down as a prop. If you truly want the visitor's local time, show a neutral value first and replace it in an effect. For ids, use useId rather than Math.random.

TypeScript· Deterministic date formatting, identical on any machine
const formatter = new Intl.DateTimeFormat("en-IN", {
  dateStyle: "medium",
  timeStyle: "short",
  timeZone: "Asia/Kolkata",
});

export function formatPublished(iso: string): string {
  return formatter.format(new Date(iso));
}

Invalid nesting, and when suppressHydrationWarning is acceptable

For nesting errors, the fix is to correct the structure. A p element can contain only phrasing content, so replace a wrapping p with a div, or replace the inner div with a span. If a component library renders a block element inside your paragraph, change the wrapper rather than the library. Validate the final markup by looking at the rendered HTML from view-source.

The suppressHydrationWarning prop tells React to ignore a mismatch on that one element's text content or attributes. It is meant for the narrow case where a difference is unavoidable and harmless, for example a timestamp rendered in a single span, or the class or style attribute that a theme script sets on the html element before React runs. It only applies one level deep and does not fix mismatched structure. Used broadly, it hides real bugs and leaves the DOM out of sync with React's expectations, so treat it as a last resort rather than a first response.

TSX· The narrow, legitimate use: one element whose text always differs
export function RenderedAt() {
  return (
    <time suppressHydrationWarning dateTime={new Date().toISOString()}>
      {new Date().toLocaleTimeString("en-IN")}
    </time>
  );
}

Practical tip: when the error appears only on some machines, compare the server's timezone and locale with the browser's. Running the dev server with a different TZ environment variable than your browser uses is a quick way to reproduce date-formatting mismatches on your own laptop.

Confirm the fix and prevent a repeat

Reload the page with the console open, using a private window with extensions off, and confirm no hydration message appears. Reload several times, since a mismatch caused by Math.random or a clock tick can pass occasionally. Then build for production and run the production server, because some warnings are development-only and production behaviour on a mismatch is to patch the DOM silently.

To prevent the error, adopt a simple rule: render functions must be pure for the same props and state. Read the clock, storage, window size and cookies inside effects or event handlers, never in the render body. Keep one formatting helper with explicit locale and time zone and use it everywhere. Run an HTML validator or an ESLint rule for invalid nesting during review, and when you add a third-party widget, check whether it assumes a browser and wrap it in a dynamic import if so. For related rendering questions, the guides on React Server Components and Core Web Vitals explain why server output and client output need to agree.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.