Magic Tools
Developer ToolsBy CooconAugust 5, 2026118 views4 min read

Next.js Full-Site Hydration Mismatch: The Root Cause is GTM-Loaded AdSense, Not Your Code

1. Problem Description

Next.js (App Router) site console randomly shows hydration warnings:

A tree hydrated but some attributes of the server rendered HTML
didn't match the client properties.

It's "random" because the reproduction pattern is extremely odd:

  • Cold cache (first visit / hard refresh) opening the first page: console clean
  • Any subsequent pages opened: always report errors
  • Errors are unrelated to specific pages—tool pages, article pages, home page can all trigger it
  • Reproducible in both local dev and production

Following the usual approach, checked all suspicious components: no Date.now() or Math.random() directly in rendering, no typeof window conditional rendering, no browser plugin injections (incognito mode still reports). The page code is clean.

2. Environment

Item Details
Framework Next.js 16 (App Router, React 19)
Tagging Google Tag Manager inline snippet (directly output from layout.tsx, for GSC site verification)
Ads AdSense auto-ads, loaded via GTM

3. Troubleshooting Process

Step 1: Get the full error diff. The warnings in the console are collapsed, so you can't see which attributes don't match. Use Playwright headless browser to capture:

page.on("console", async (msg) => {
  // 注意:msg.text() 只有 "%s" 占位符,拿不到实际内容
  for (const arg of msg.args()) {
    console.log(await arg.evaluate(String));
  }
});
await page.goto(url, { waitUntil: "load" }); // dev 模式 networkidle 永不触发

Two pitfalls that can waste time:

  • msg.text() for React's multi-argument console calls only returns the %s placeholder; you must iterate over msg.args() and evaluate each to get the full diff
  • In dev mode, HMR's long connection makes networkidle never satisfied, so use load as the wait condition

Step 2: Read the diff. The full output shows the mismatch occurs in the GTM inline script in <head>—React expects that position to have the GTM snippet directly output from our layout.tsx, but in the actual DOM, that position has a pagead2.googlesyndication.com script tag.

Step 3: Explain the timing difference between cold and hot cache. This is the most interesting part:

  1. The GTM snippet is directly output in the SSR HTML (must be direct for Google site verification)
  2. After GTM starts, it loads AdSense auto-ads, which dynamically inject their own script into <head>
  3. During React hydration, scripts in head are matched by position
  4. Cold cache: AdSense script needs to download first, injection happens after hydration → match is normal, console clean
  5. Hot cache: AdSense script loads instantly, injection happens before hydration → an extra script appears in head not in server-side HTML, exactly colliding with the inline GTM script React expects to match → error

The characteristic of "cold cache first page clean, subsequent pages always report" perfectly corresponds to "whether the script is already in browser cache"—this is not a code bug, but a race condition between third-party script injection and React hydration, whoever is faster wins.

4. Fix: One Attribute, But Apply It Correctly

Add suppressHydrationWarning to the GTM inline script in layout.tsx:

<script
  id="gtm"
  suppressHydrationWarning
  dangerouslySetInnerHTML={{ __html: gtmSnippet }}
/>

This attribute simply tells React "this node's mismatch is expected, don't warn"—the SSR output HTML won't change a single byte, and GSC site verification remains unaffected.

A Seemingly More 'Proper' but Incorrect Solution

Changing GTM to next/script with strategy="afterInteractive" can also suppress the warning, but don't do this: afterInteractive means the GTM snippet no longer appears in the SSR HTML, while Google site ownership verification (HTML tag method) and some crawler detections rely on the snippet directly output in the initial HTML. Sacrificing site verification for a harmless warning is not worth it.

5. Verification

Before and after the fix, use the same Playwright script to scan major site pages:

  • Before fix: 4 out of 5 pages reported hydration warnings (the only clean one was the cold cache first page)
  • After fix: 5/5 all clean, SSR HTML diff zero

6. Is This Issue Worth Fixing?

Hydration mismatch warnings don't affect functionality—React will continue running with client-side as the source. But leaving it unfixed has two practical costs:

  1. It will drown out real warnings. When the entire site commonly reports errors, if your own components ever have hydration issues, no one will notice an extra line.
  2. Troubleshooting costs will be passed on to the future. Every new colleague (or future you) seeing red text in the console will re-investigate, and since this root cause is hidden deep, each round isn't cheap.

7. Troubleshooting Mantras

  • Hydration warnings first check reproduction pattern: if all pages report and it's unrelated to page code → investigate global injections (tagging, ads, browser plugins), don't check components one by one
  • Cold cache clean, hot cache always reports → race condition type issue, suspect "third-party scripts whose loading speed changes"
  • Collapsed React warnings use Playwright msg.args() to evaluate each for the full text, don't guess with ellipses
  • suppressHydrationWarning should only be used on nodes where the root cause is confirmed and the mismatch is expected—it's an exact exemption, not a silencer

Related Articles

Dev Breakfast · 2026-09-19

Today's headline: The Internal Repo Earned by a Single HEIC Image: OpenAI Forum's SSO Vulnerability. Plus 4 more: ZCode Silently Uploads 313MB Encrypted Package, Keys Only on the Server; Telstra Outage for a Night: One GPS Receiver Sent the National Network Back to 2006; and more.

daily-intelSep 19, 202610 min
23

Dev Breakfast · 2026-09-18

Today's headline: AWS says some data in Middle East facilities can't be recovered: backup is harder than you think. Plus 7 more: Nvidia allows Rust to directly write GPU kernels, with two paths in parallel; 4B model-generated query plans are 81% faster than Postgres; and more.

daily-intelSep 18, 20269 min
48

Service Up, Ports Open, Certs Valid, VPN Dead for 4 Hours: Tailscale Took Over DNS and Left the Proxy Box With No Upstream

A Los Angeles VPS running sing-box (VLESS-REALITY + Hysteria2) lost its VPN the day after Tailscale was installed. systemctl, ports and certificates were all fine. The root cause was in /etc/resolv.conf: Tailscale manages DNS by default, the tailnet had no global nameservers, and when dhclient renewed its lease tailscaled read an empty resolv.conf and dropped its upstream list. From then on every public domain got SERVFAIL, and the REALITY handshake could not even resolve www.apple.com. Full timeline, the evidence for each step, three fixes, and the rules we added to CLAUDE.md so an AI assistant (Claude Code) does not walk into this again.

claude-codetroubleshooting+8
pitfallsSep 17, 20266 min
48

Dev Breakfast · 2026-09-17

Today's headline: Firefox 156 pushes 'Suggest' ads in the address bar, PDF starts up 45% faster. Plus 7 more: Karpathy's autoresearch six months later: Shopify uses it to improve 40+ metrics, rekursiv refreshes nanochat record in three days; Replacing actions/setup-go: Golang CI scaling actual test; and more.

daily-intelSep 17, 20266 min
75

Published by Magic Tools