Skip to content

Bug: hydration mismatch when a suspended <head> (HostSingleton) is replayed — singleton-scope cursor is saved twice #37551

Open

Description

@stevezhong9

When the children of <head> suspend during hydration and React later replays the head fiber (replaySuspendedUnitOfWork), claimHydratableSingleton runs a second time and overwrites previousHydratableOnEnteringScopedSingleton with the cursor that is already inside <head>. When head pops, the cursor is "restored" to that in-head node instead of body.firstChild, the first element under <body> finds no matching hydratable node, and React reports Hydration failed because the server rendered HTML didn't match the client (#418, args[]=HTML in production) and client-renders the whole tree — although server and client markup are identical.

replayBeginWork re-syncs the hydration cursor for HostComponent only (added in #35494 for #35210). The comment there says other fiber types "aren't reliant on the cursor positioning", but head is a singleton scope (isSingletonScope) that saves/restores the cursor on enter/exit, so it is.

React version: [email protected] (latest canary at the time of writing) and [email protected]. Also hit in production with Next.js 16.3.4 (bundled 19.3.0-canary-cbb046ab-20260731): a 'use client' module export used as a prop inside <head> becomes a client reference, so the <script> element under <head> is a blocked lazy until that chunk loads; whether the chunk has loaded before hydration reaches <head> is a race, so the error is intermittent and page-dependent.

Steps To Reproduce

  1. mkdir repro && cd repro && npm init -y && npm i react@canary react-dom@canary jsdom
  2. Save the script below as repro.js
  3. node repro.js head → hydration error (the bug)
  4. Controls: node repro.js body (same thenable under a <div>) → fine on canary; node repro.js head sync (hydrateRoot outside startTransition) → fine on canary, because a sync render unwinds instead of replaying

Link to code example: self-contained script (jsdom is the only dependency besides React; same environment as React's own tests):

'use strict'
const where = process.argv[2] || 'head'
const lane = process.argv[3] || 'transition'

const React = require('react')
const { renderToString } = require('react-dom/server')
const h = React.createElement

const SCRIPT = h('script', { dangerouslySetInnerHTML: { __html: '/* inline init script */' } })
const LEAF = h('p', null, 'hello')
const App = ({ headChild, bodyChild }) =>
  h('html', { lang: 'en' }, h('head', null, headChild), h('body', null, h('div', { className: 'app' }, bodyChild), h('footer', null, 'footer')))

// Server: everything resolved.
const html = renderToString(h(App, { headChild: SCRIPT, bodyChild: LEAF }))

// Client environment.
const { JSDOM } = require('jsdom')
const dom = new JSDOM(html)
global.window = dom.window
global.document = dom.window.document
for (const k of ['Node', 'Element', 'HTMLElement', 'Text', 'Comment', 'DocumentFragment', 'Event', 'CustomEvent', 'MutationObserver', 'HTMLIFrameElement']) {
  if (!(k in global)) global[k] = dom.window[k]
}
const ssrDiv = document.querySelector('.app')

// A thenable with no `status` yet that settles in a microtask once `then` is called. This is the shape an RSC
// client-reference / lazy chunk presents to the reconciler (its `status` becomes "fulfilled" when the chunk loads),
// so React takes the replaySuspendedUnitOfWork path instead of unwinding.
const lateThenable = (value) => ({ then(resolve) { queueMicrotask(() => resolve(value)) } })

const { hydrateRoot } = require('react-dom/client')
const props = where === 'head' ? { headChild: lateThenable(SCRIPT), bodyChild: LEAF } : { headChild: SCRIPT, bodyChild: lateThenable(LEAF) }
const errors = []
const hydrate = () => hydrateRoot(document, h(App, props), { onRecoverableError: (e) => errors.push(String(e.message).split('\n')[0]) })
if (lane === 'transition') React.startTransition(hydrate) // what Next.js does
else hydrate()

setTimeout(() => {
  console.log(JSON.stringify({ react: require('react-dom/package.json').version, where, lane, recoverableErrors: errors, bodyDivReused: document.querySelector('.app') === ssrDiv }, null, 2))
  process.exit(errors.length ? 1 : 0)
}, 300)

The current behavior

head (transition) body (transition) head sync
19.3.0-canary-6c0e1047-20260908 error, <div class="app"> re-created ok ok
19.2.8 error error (expected: #35494 is not in 19.2) error

node repro.js head on the canary:

{
  "react": "19.3.0-canary-6c0e1047-20260908",
  "where": "head",
  "lane": "transition",
  "recoverableErrors": [
    "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:"
  ],
  "bodyDivReused": false
}

With NODE_ENV=production: Minified React error #418; visit https://react.dev/errors/418?args[]=HTML&args[]=.

Trace from the dev build with console.log at the relevant points:

renderRootConcurrent
claimSingleton html   cursor=<div.app>  prevSaved=null
claimSingleton head   cursor=<div.app>  prevSaved=null        ← saves body.firstChild, cursor := head.firstChild (<script>)
                                                              ← reconciling head's children throws (thenable pending)
readyToContinue status=fulfilled unit=head
REPLAY tag=27 type=head cursor=<script> isHydrating=true      ← replayBeginWork → default branch → beginWork(head) again
claimSingleton head   cursor=<script>   prevSaved=<div.app>   ← overwrites the saved cursor with <script> (already inside head)
popSingleton   head   restoreTo=<script>                      ← cursor "restored" to <script>
claimSingleton body   cursor=<script>
MISMATCH fiber=div cursor=<script> parent=body                ← body's first element looks for a match among head's children

The expected behavior

No hydration error: server and client render the same markup; the child of <head> merely arrives late.

Where in the code

  • packages/react-reconciler/src/ReactFiberWorkLoop.js — replayBeginWork: case HostComponent calls popHydrationStateOnInterruptedWork(unitOfWork) with the comment "Other fiber types hydrate differently and aren't reliant on the cursor positioning so this function is only for HostComponent". HostSingleton falls into default, which does unwindInterruptedWork + resetWorkInProgress + beginWork, i.e. claimHydratableSingleton runs again.
  • packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js — getFirstHydratableChildWithinSingleton: for isSingletonScope(type) (head) it unconditionally does previousHydratableOnEnteringScopedSingleton = currentHydratableInstance, so a re-entry saves the in-scope cursor.
  • unwindInterruptedWork for HostSingleton only pops the host context; nothing restores previousHydratableOnEnteringScopedSingleton.

A native Promise child happens to mask the bug: on resume its status is still "pending" from React's point of view, so React unwinds to the root and re-hydrates from scratch. A thenable whose status is "fulfilled" by the time React resumes (Flight chunks, or the bare thenable above) takes the replay path.

Possible fixes (either seems enough)

  1. In replayBeginWork, treat HostSingleton like HostComponent when the replayed fiber is hydrationParentFiber: pop to the next host parent and restore nextHydratableInstance (and, for a singleton scope, previousHydratableOnEnteringScopedSingleton) before re-running beginWork.
  2. Or make the singleton-scope enter/exit re-entrant, e.g. skip saving when the singleton fiber is already hydrationParentFiber.

Happy to turn this into a PR with a regression test if that helps.

Activity

  1. GorkemMergenay commented on Sep 24, 2026

    @GorkemMergenay

    Additional data point from a production Next.js 16.3.4 app (bundled [email protected]), same trigger as described above: a 'use client' export used as dangerouslySetInnerHTML.__html of a <script> in the root layout's <head>, so the RSC payload carries "__html":"$19" → 19:I[…,"themeBootstrapScript"].

    The rate depends heavily on the browser. Cold loads of three App Router pages. The unfixed build and a build with the app-side workaround below were served side by side and loaded alternately in the same time window:

    before workaround after workaround
    Playwright WebKit 26.5 25/33 loads reported #418 0/33
    Playwright Chromium 5/33 reported (7/33 hit the corrupted cursor) 0/33
    Real Safari 27.0 (13 views × 4 rounds) 36/52 views 0/52

    Chromium usually hides it. With throwOnHydrationMismatch instrumented, the corrupted cursor is still captured in Chromium: the fiber is the first <body> child, and nextHydratableInstance is <meta charset="utf-8">, whose parent is <head>. But the root render then restarts and discards that attempt, so onRecoverableError often never fires. WebKit and Safari keep the single root render and report it. That may be why this mostly surfaces as "Safari-only" #418 reports. In all 48 captures across both engines the signature was identical.

    Impact: the mismatch sits above every Suspense boundary, so each reported #418 discarded and client-rendered the whole document. The parser-inserted first <body> element was replaced in 4/4 measured cases.

    App-side workaround until #37630 lands: keep everything rendered inside the root <head> free of client references. We moved the string into a module without 'use client', so the RSC payload inlines it ("__html":"…" instead of "__html":"$19"). That brought all three browsers above to 0.

  2. toddagent01 commented on Nov 18, 2026

    @toddagent01

    Another data point, with a different trigger for the <head> suspension — this one is dev-only.

    Setup. Payload CMS v4 beta admin on Next.js 16.4.6, react/react-dom 19.3.1. Payload's server root layout creates a <meta name="viewport"> element on the server and passes it as a prop into a client component that renders it inside <head> (reported to Payload as payloadcms/payload#19697).

    Trigger. In Next dev, that element's Flight debug rows (owner/stack) are streamed separately over the dev websocket. When they arrive after hydration has started, the element is still a blocked chunk, so <head> suspends — and the replay corrupts the singleton cursor exactly as described in this issue. Whether it fires is pure dev-server timing: one long-running dev server failed almost every load of some admin views, while a freshly restarted server never failed. Production builds have no debug channel and are unaffected.

    Instrumented confirmation of the mechanism. Watching the singleton hydration path in the browser: every failing load entered <head> twice, and on the second entry the saved cursor was overwritten with a node inside <head>; clean loads entered <head> once. <body> then hydrated against <head>'s nodes (first <body> child matched against <head>'s <style>/<script> nodes).

    Both suggested fixes check out from the app side. Keeping the saved position across the replay (option 2 — don't overwrite previousHydratableOnEnteringScopedSingleton when re-entering the scope) took the failing server from 3/3 failing loads to 0/4. Removing the server-made element from <head> (so nothing in <head> can suspend) gave 0/6 against 3/3 unmodified at the same moment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions