Skip to content
Latchkey

Next.js "Hydration failed" - Fix in CI

React hydration requires the server HTML to match the first client render exactly. Non-deterministic values (dates, randoms), browser-only branches, or invalid HTML nesting break the match.

What this error means

The page errors at runtime with Hydration failed because the server rendered HTML didn't match the client; strict E2E checks fail the pipeline on it.

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

  at throwOnHydrationMismatch (react-dom.development.js)

Common causes

Non-deterministic render

Rendering Date.now(), Math.random(), or localStorage produces different markup on server and client.

Invalid HTML nesting

A <p> wrapping a <div> (or similar) is auto-corrected by the browser, so the client tree differs from the server string.

How to fix it

Defer client-only values

  1. Render dynamic values after mount so the first client render matches the server.
component.tsx
const [now, setNow] = useState(null);
useEffect(() => setNow(Date.now()), []);
return <span>{now ?? ''}</span>;

Fix invalid HTML nesting

  1. Make markup valid so the browser does not restructure it.
component.tsx
// invalid: <p><div/></p>  ->  valid:
<div><div /></div>

How to prevent it

  • Keep render output deterministic; move browser-only reads into effects.
  • Validate HTML nesting to avoid browser auto-correction.

Frequently asked questions

What causes "Hydration failed"?
Rendering Date.now(), Math.random(), or localStorage produces different markup on server and client.
How do I fix Hydration failed?
Defer client-only values

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card