
Learn how to diagnose and fix pesky React hydration mismatch errors in Next.js App Router with practical code patterns.
When you build modern web apps with Next.js and the App Router, you experience incredible speeds thanks to Server-Side Rendering (SSR). But SSR comes with its own set of debugging challenges. If you have ever opened your browser console to find a wall of red text shouting about text content mismatch or server-client tree discrepancies, you have met the dreaded React hydration error.
As a full-stack developer working on client projects worldwide, I run into this issue frequently when setting up server components that rely on browser-specific APIs, dates, or window dimensions. Let's look at why this happens and how you can fix it permanently.
The most common error message you will see in your developer tools looks something like this:
Error: Text content does not match server-rendered HTML.
Warning: Expected server HTML to contain a matching <div> in <div>.
Sometimes it manifests as an abrupt flash of unstyled content or UI elements shifting drastically after the page loads. Your users might click a button before the JavaScript finishes loading, causing the application to crash or behave unexpectedly.
React hydration is the process where the client-side JavaScript takes the static HTML rendered by the server and attaches event listeners, turning it into an interactive tree.
During SSR, Next.js runs your component code on the server and generates HTML. Then, your browser downloads that HTML and runs the exact same component code on the client. If the HTML generated on the server does not match the initial HTML generated on the client during that first render, React throws a hydration error.
Common culprits include:
window, document, or localStorage during initial render.new Date().window.innerWidth).<p> tag inside another <p> tag) which browsers auto-correct differently than React expects.Let's walk through a practical scenario. Imagine you have a component that displays a greeting based on whether a user is logged in, checking localStorage right away.
// components/Greeting.tsx
export default function Greeting() {
const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null;
return (
<div>
{token ? <p>Welcome back, user!</p> : <p>Please log in.</p>}
</div>
);
}
On the server, window is undefined, so token is always null. The server renders <p>Please log in.</p>. On the client, if the user has a token in localStorage, it renders <p>Welcome back, user!</p>. Boom—hydration mismatch.
To fix this safely in the Next.js App Router, you should defer the client-only check until after the component has mounted on the client.
'use client';
import { useState, useEffect } from 'react';
export default function Greeting() {
const [isMounted, setIsMounted] = useState(false);
const [token, setToken] = useState<string | null>(null);
useEffect(() => {
setIsMounted(true);
setToken(localStorage.getItem('token'));
}, []);
// Return a safe fallback during SSR and initial hydration
if (!isMounted) {
return <div>Loading...</div>;
}
return (
(
<div>
{token ? <p>Welcome back, user!</p> : <p>Please log in.</p>}
</div>
)
);
}
By rendering a neutral loading state (or nothing at all) until useEffect runs, the server output and the initial client render match completely. Once mounted, the state updates and renders the correct UI.
'use client' when you genuinely need interactivity, state, or browser APIs.ssr: false.import dynamic from 'next/dynamic';
const Chart = dynamic(() => import('@/components/Chart'), {
ssr: false,
loading: () => <p>Loading chart...</p>,
});
Need help optimizing your Next.js application, improving your web vitals, or building a high-performance web app or API? Feel free to get in touch.
Tagged with
Leave a comment