Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

React hydration failed: the server HTML and the first browser render differ

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

Short answer

Hydration fails when the first render in the browser produces different HTML from the HTML the server sent. React 19 prints a diff: lines with + are the browser's version, lines with - the server's. The usual causes are window or localStorage read during render, time, random or locale-dependent values, invalid nesting such as a div inside a p, and extensions or CDNs editing the page.

  • Applies to Next.js 15, Next.js 16, React 19.2, React 18 (older message wording)
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Reproduce it in development and read the block printed under the error, in the browser console or the Next.js error overlay. The indented tags are the component path down to the node that differs. The line starting with + is what the browser rendered, the line starting with - is what the server sent. What differs between those two lines points to one of the causes below.

    npm run dev
    # load the page, open DevTools > Console and read the diff, for example:
    #   <OrderSummary>
    #     <time>
    # +     16/11/2026, 14:05      <- browser
    # -     11/16/2026, 9:05 AM    <- server
  2. 2Match what you see, then jump to its fix

    1. 1The diff shows two branches of the same component: the server drew the fallback (signed out, light theme, wide layout) and the browser drew the real state.A browser-only value is read while renderingFix
    2. 2The + and - lines carry the same date in two formats or two time zones, two different numbers, or two different generated ids.Time, random values or locale formatting are computed during renderFix
    3. 3The diff shows the same content in a different element tree, usually around a p, an a or a button, and React logs a nesting warning in development.The JSX produces HTML that is not allowed to nestFix
    4. 4Only you or one tester sees it, it disappears in a private window, and the diff shows attributes or nodes your code never writes, often on html or body.A browser extension edits the page before React startsFix
    5. 5Development is clean but production fails, or only Safari on iPhone fails; the diff shows text that became a link, or whitespace and comments that vanished.The HTML changes between the server and the browserFix

What does the error look like?

  • Hydration failed because the server rendered HTML didn't match the client. As a result this tree will be regenerated on the client.
  • Text content does not match server-rendered HTML
  • https://react.dev/link/hydration-mismatch

Cause 1 of 5

A browser-only value is read while rendering

1Check

Look through the components on that path for window, document, localStorage, matchMedia or navigator used in the function body, or for a branch on typeof window. None of these exist on the server, so the server and the first browser pass take different branches.

grep -rnE "typeof window|localStorage|sessionStorage|matchMedia|navigator\.|document\." \
  app components src --include=*.tsx --include=*.jsx 2>/dev/null

2Fix

Make the first browser render match the server, then switch to the real value. useSyncExternalStore does this cleanly: React calls getServerSnapshot on the server and again during hydration, then reads the live value. For a widget that only makes sense in a browser (a map, an editor), load it with next/dynamic and ssr: false from inside a Client Component; Server Components refuse that option.

'use client'
import { useSyncExternalStore } from 'react'

const query = '(max-width: 640px)'

function subscribe(onChange: () => void) {
  const mq = window.matchMedia(query)
  mq.addEventListener('change', onChange)
  return () => mq.removeEventListener('change', onChange)
}

export function useIsNarrow() {
  return useSyncExternalStore(
    subscribe,
    () => window.matchMedia(query).matches, // browser, after hydration
    () => false,                            // server and hydration pass
  )
}

3Verify

Keep a browser test that fails on any hydration error and run it against the page. Hydration errors can surface as console errors or as uncaught page errors, so it listens to both.

// e2e/hydration.spec.ts (Playwright)
import { test, expect } from '@playwright/test'

test('pricing hydrates cleanly', async ({ page }) => {
  const errors: string[] = []
  page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()) })
  page.on('pageerror', (e) => errors.push(e.message))
  await page.goto('http://localhost:3000/pricing')
  await page.waitForLoadState('networkidle')
  expect(errors.filter((e) => /hydrat/i.test(e))).toEqual([])
})
Did this fix it?

Cause 2 of 5

Time, random values or locale formatting are computed during render

1Check

The server usually runs in UTC with one locale; the browser uses the visitor's zone and language. Print what each side resolves, and search render code for Date.now(), new Date(), Math.random() and crypto.randomUUID().

# on the server
node -e "console.log(Intl.DateTimeFormat().resolvedOptions())"
// in the browser console
Intl.DateTimeFormat().resolvedOptions()

2Fix

Choose one place where the value is produced. Format dates in a Server Component and pass the finished string down, so the browser never formats it again; if a Client Component must format, pass an explicit locale and timeZone. Generate element ids with useId instead of random numbers. For text that is meant to differ, such as a relative time, put suppressHydrationWarning on that single element: it silences only that element's own text and attributes, and React will not patch the text.

// app/orders/[id]/page.tsx  (Server Component: formatted once, on the server)
const fmt = new Intl.DateTimeFormat('en', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' })

export default async function Page({ params }: PageProps<'/orders/[id]'>) {
  const { id } = await params
  const order = await getOrder(id)
  return <OrderSummary placedAt={fmt.format(order.createdAt)} />
}

// in a Client Component: an id that is the same on both sides
const fieldId = useId()

3Verify

Run the browser test from the first cause with a time zone and language far from the server's. If the page still hydrates cleanly there, no formatted value depends on where it runs.

// playwright.config.ts
export default defineConfig({
  use: { timezoneId: 'Pacific/Kiritimati', locale: 'de-DE' },
})
Did this fix it?

Cause 3 of 5

The JSX produces HTML that is not allowed to nest

1Check

Browsers repair some invalid markup while parsing: a p closes itself as soon as a div starts, and a link inside a link gets split. The DOM built from the server HTML is then not the tree React expects. After the error, React rebuilds that tree in the browser with the invalid nesting intact, so a selector in the console finds the offending pairs.

// DevTools console, after the hydration error
document.querySelectorAll('p div, p p, p ul, p ol, p table, a a, button button, form form')

2Fix

Change the outer element: a p that has to hold block content becomes a div, and a clickable card becomes one link with plain content instead of a link that wraps other links or buttons. Check UI-library components too, because the p or div they render is not visible in your JSX.

// before: <Badge /> renders a <div>, and a <p> may not contain it
<p className="lead"><Badge /> {text}</p>

// after
<div className="lead"><Badge /> {text}</div>

3Verify

Reload and run the selector again: it should return an empty list, and the console should show neither the nesting warning nor the hydration error.

document.querySelectorAll('p div, p p, a a, button button').length  // expect 0
Did this fix it?

Cause 4 of 5

A browser extension edits the page before React starts

1Check

Open the same URL in a clean browser profile with no extensions. Translators, password managers, grammar tools and dark-mode tools inject attributes and elements early. React 19 skips unknown tags in head and body, but changes to html or body attributes, or inside your own tree, still count as mismatches.

# macOS: Chrome with a fresh, extension-free profile
open -na "Google Chrome" --args --user-data-dir="$(mktemp -d)" http://localhost:3000/pricing
# Linux
google-chrome --user-data-dir="$(mktemp -d)" http://localhost:3000/pricing

2Fix

There is nothing wrong in your code. If the extension only adds attributes to html or body, put suppressHydrationWarning on those two elements in the root layout. It reaches one level deep, so real mismatches inside your components are still reported.

// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" suppressHydrationWarning>
      <body suppressHydrationWarning>{children}</body>
    </html>
  )
}

3Verify

Reload with the extension switched on: the error is gone. Then add a deliberate mismatch inside a component for one run; it must still be reported, which proves nothing real was hidden.

// temporary, inside any Client Component; remove after the check
<span>{Date.now()}</span>
Did this fix it?

Cause 5 of 5

The HTML changes between the server and the browser

1Check

Fetch the page from the app itself and through the public URL, then compare. A CDN or edge feature that minifies or rewrites HTML changes it after React rendered it. iOS turns phone numbers, email addresses and street addresses into links.

curl -s http://127.0.0.1:3000/pricing -o origin.html
curl -s https://example.com/pricing -o edge.html
diff <(tr '>' '\n' < origin.html) <(tr '>' '\n' < edge.html) | head -40

2Fix

Turn off HTML rewriting (minification and similar features) at the CDN for pages Next.js renders, and switch off iOS auto-linking with formatDetection in the root metadata.

// app/layout.tsx
import type { Metadata } from 'next'

export const metadata: Metadata = {
  formatDetection: { telephone: false, email: false, address: false },
}

3Verify

Run the same diff: apart from per-request values, the two files should match. Then open the page on an iPhone and confirm the console stays clear.

diff <(tr '>' '\n' < origin.html) <(tr '>' '\n' < edge.html) | wc -l
Did this fix it?

How do I stop it coming back?

  • Keep render pure: anything that comes from window, the clock or a random source goes into an effect or useSyncExternalStore, never into the function body.
  • Format dates and money in Server Components, or with an explicit locale and time zone everywhere.
  • Run a browser test that fails on hydration errors in CI, with a time zone that differs from the server's.
  • Use suppressHydrationWarning only on single elements whose difference you can name, never on a wrapper to make an error go away.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Web apps

next/link throws React.Children.only on its children

Error: React.Children.only expected to receive a single React element child.

React.Children.only accepts exactly one React element and throws for anything else, including an array with one item.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.