MD. NAZMUL ISLAM
HomeServicesPortfolioCase StudiesBlogAboutContact
ResumeLoginSign Up
Fixing React Hydration Errors in Next.js App Router
  1. Home
  2. Blog
  3. Fixing React Hydration Errors in Next.js App Router
Back to Blog
Next.jsReactApp RouterWeb DevelopmentDebugging

Fixing React Hydration Errors in Next.js App Router

November 29, 20264 min read0 views0 comments

Learn how to diagnose and fix pesky React hydration mismatch errors in Next.js App Router with practical code patterns.

Fixing React Hydration Errors in Next.js App Router

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 Problem and Its Symptoms

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.

Why Hydration Mismatches Happen

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:

  • Using window, document, or localStorage during initial render.
  • Rendering dynamic dates or times using new Date().
  • Browser extensions modifying the DOM before React loads.
  • Conditional rendering based on viewport size (window.innerWidth).
  • Invalid HTML nesting (like a <p> tag inside another <p> tag) which browsers auto-correct differently than React expects.

Step-by-Step Fix With Working Code

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.

The Broken Component

// 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.

The Correct Fix

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.

How to Check It Worked

  1. Clear your browser cache and hard-refresh the page.
  2. Open your browser console and verify that the red hydration error warnings are completely gone.
  3. Check your network tab to ensure your server components are streaming correctly without blocking the main thread.
  4. Test with browser extensions (like dark mode toggles or ad blockers) disabled and enabled to ensure they don't trigger unexpected DOM mutations during hydration.

How to Prevent Future Hydration Bugs

  • Embrace Server Components: Keep data fetching and static markup in Server Components where possible. Only drop down to 'use client' when you genuinely need interactivity, state, or browser APIs.
  • Use Dynamic Imports for Heavy Client Libraries: If you use a library that relies heavily on window objects (like charting libraries), load it with Next.js dynamic imports and ssr: false.
import dynamic from 'next/dynamic';

const Chart = dynamic(() => import('@/components/Chart'), {
  ssr: false,
  loading: () => <p>Loading chart...</p>,
});
  • Validate Your HTML: Use semantic HTML tags correctly. Never nest block elements inside inline elements.

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

Next.jsReactApp RouterWeb DevelopmentDebugging

Comments

Leave a comment

You must be signed in to comment.

MD. NAZMUL ISLAM

Full-Stack & React Native Developer

Send a project enquiry

Navigation

  • Home
  • About
  • Services
  • Case Studies
  • Blog
  • Contact
  • 한국어 (Korean)

Services

  • Web Development
  • Mobile App Development
  • Custom Software & SaaS
  • SEO & Marketing
  • Domain & Hosting

© 2026 MD. Nazmul Islam. All rights reserved.

Privacy Policy·Terms of Service