Hydration failed because the server rendered HTML didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used:
A server/client branch if (typeof window !== 'undefined').
Variable input such as Date.now() or Math.random() which changes each time it's called.
Date formatting in a user's locale which doesn't match the server.
External changing data without sending a snapshot of it along with the HTML.
Invalid HTML tag nesting.
It can also happen if the client has a browser extension installed which messes with the HTML before React loaded.
This is a very common and important error message in Next.js (and other SSR frameworks like Remix). Let's break down what it means and how to fix it, based on the points provided.
What is Hydration?
Server-Side Rendering (SSR): Next.js pre-renders your page into HTML on the server. This HTML is sent to the browser for a fast initial display and good SEO.
Client-Side Takeover: Once the HTML and JavaScript arrive in the browser, React "hydrates" the static HTML. This means it attaches event listeners and makes the page interactive, essentially taking control of the DOM elements the server rendered.
The Mismatch: Hydration expects the HTML structure rendered by the server to be identical to what the React component would render on its first pass on the client. If there's a difference, React gets confused. It can't reliably map its virtual DOM to the existing DOM.
The "Fix": When a mismatch occurs, React discards the server-rendered HTML for that part of the tree and re-renders it from scratch on the client. This negates some benefits of SSR (like a fast non-interactive paint) and can cause a visual flicker.
Common Causes and Solutions (as listed in your error):
if (typeof window !== 'undefined') (or similar environment checks)
Problem: On the server, typeof window is 'undefined'. On the client, it's 'object'. If your component's initial render output changes based on this, you'll have a mismatch.
jsx
// Problematic
function MyComponent() {
if (typeof window !== 'undefined') {
return <p>Rendered on Client</p>;
}
return <p>Rendered on Server</p>; // This is what server sends
}
// Client will initially expect "Rendered on Server" but then try to render "Rendered on Client"
Solution: Defer client-specific rendering until after hydration using useEffect and state.
jsx
// Corrected
import { useState, useEffect } from 'react';
function MyComponent() {
const [isClient, setIsClient] = useState(false);
useEffect(() => {
setIsClient(true);
}, []);
if (!isClient) {
return <p>Rendered on Server (or placeholder)</p>; // Initial render for both server and client
}
// This part only renders on the client *after* the initial hydration
return <p>Rendered on Client (with window access)</p>;
}
Or, for simpler cases where you just want to conditionally render something small only on the client, and it's okay if it's not there during SSR:
jsx
import { useState, useEffect } from 'react';
function ClientOnlyComponent({ children }) {
const [hasMounted, setHasMounted] = useState(false);
useEffect(() => {
setHasMounted(true);
}, []);
if (!hasMounted) {
return null; // Or a loading spinner, or a placeholder
}
return <>{children}</>;
}
// Usage
<ClientOnlyComponent>
<p>My window-dependent content: {window.innerWidth}px</p>
</ClientOnlyComponent>
Variable input like Date.now(), Math.random()
Problem: These functions produce different values each time they are called. The server calls it once, the client calls it again during its initial render pass – the values will differ.
jsx
// Problematic
function MyComponent() {
const id = Math.random();
return <div id={`item-${id}`}>Hello</div>;
}
Solution:
If the value must be random but consistent for a component instance, generate it once and store it in state, typically initialized in useEffect (if client-only) or pass it as a prop from a server component.
For timestamps that you want to display, fetch them server-side or use useEffect to set them client-side.
If it's an attribute like an ID that needs to be unique but doesn't need to be random, use React's useId hook (React 18+).
Sometimes, for display purposes like "Last updated: just now", you might intentionally want it to be different and can suppress the warning (see below).
Date formatting in a user's locale which doesn't match the server
Problem:new Date().toLocaleTimeString() might use the server's locale (e.g., en-US) during SSR, but the client browser's locale (e.g., de-DE) during client-side rendering.
jsx
// Problematic
function MyComponent() {
const time = new Date().toLocaleTimeString();
return <p>Current time: {time}</p>;
}
Solution:
Format dates consistently: Pass the locale explicitly if possible, or pass the raw timestamp/ISO string from the server and format it only on the client side using useEffect.
Use suppressHydrationWarning (use with caution): If the difference is acceptable and expected (e.g., a timestamp that's meant to be "live").
jsx
// With suppression
function MyComponent() {
const [time, setTime] = useState('');
useEffect(() => {
setTime(new Date().toLocaleTimeString());
}, []);
// Initial render might be empty or a placeholder
// Or, if you render the server time initially and then update:
const serverTime = new Date().toLocaleTimeString('en-US'); // Assuming server uses en-US
return (
<p suppressHydrationWarning>
Current time: {isClient ? new Date().toLocaleTimeString() : serverTime}
</p>
);
}
// A more common approach:
function TimeDisplay() {
const [currentTime, setCurrentTime] = useState(new Date().toISOString()); // Store as ISO string
useEffect(() => {
// This will run only on the client
setCurrentTime(new Date().toLocaleTimeString());
}, []);
// On the server and initial client render, it might show the ISO string
// or you can have a placeholder.
// If you must show something initially, and it *will* differ, use suppressHydrationWarning
return <span suppressHydrationWarning>{currentTime}</span>;
}
External changing data without sending a snapshot
Problem: If your component reads from localStorage, sessionStorage, or a global variable that's modified by other scripts before React hydrates, the server won't know about these values.
Solution: Access such data only within useEffect. Treat it like client-only data.
Invalid HTML tag nesting
Problem: The server renders HTML like <p><div>Hello</div></p>. Browsers will "fix" this to <p></p><div>Hello</div><p></p>. When React tries to hydrate, it sees the browser-corrected structure, which doesn't match what the server sent.
Solution: Write valid HTML. Use a linter (like ESLint with JSX A11y plugins) to catch these. Check the W3C validator if unsure.
Browser extensions messing with HTML
Problem: Some browser extensions inject elements or modify the DOM. This can happen before React hydrates.
Solution: Try disabling extensions, especially ad blockers or content modifiers, to see if the error disappears. This is harder to control for your users but good for your own debugging.
General Debugging Strategy:
Read the Full Error: The error often points to the component or even the specific DOM node where the mismatch occurs.
Inspect the HTML:
Use "View Page Source" in your browser. This shows the exact HTML the server sent.
Use the "Elements" tab in browser dev tools. This shows the DOM after the browser has parsed it (and potentially "fixed" invalid nesting) and after React has potentially re-rendered.
Compare these. Look for differences in attributes, text content, or structure around the area React complains about.
Simplify: Comment out parts of the problematic component until the error goes away. This helps isolate the exact line(s) causing the issue.
React DevTools: Can sometimes highlight hydration mismatches, though it's often more about inspecting the state after hydration.
Key Takeaway:
The goal is to ensure that the first render output of your React component on the client is identical to the HTML generated by the server. Any dynamic, client-specific rendering should be deferred until after this initial hydration, typically using useEffect.
The suppressHydrationWarning prop should be a last resort for cases where a difference is truly intentional and minor (like a timestamp differing by a few milliseconds, or a generated ID that doesn't affect structure). Overusing it can mask real bugs.