Minimal Next.js App Router app reproducing a HydrationBoundary race that
happens when a component outside the boundary that owns some SSR state
subscribes to the same query key as a component inside it.
Versions: [email protected], [email protected], @tanstack/[email protected].
npm install
npm run dev # http://localhost:3411/api/data increments a server-side counter on every call and returns
{ value, servedAt } after an artificial 400ms delay, so it's easy to tell
apart an SSR-only hit (server terminal log, counter +1 total) from an extra
client-side fetch (counter +1 and a GET /api/data request visible in the
browser's Network tab).
-
/broken— a header (AppShell) using plainuseQueryrenders outside the page's ownHydrationBoundary. The page prefetches and dehydrates only its own subtree.- Hard-reload it and check the Network tab: one extra client-side
GET /api/dataevery time, and the header's displayed value ends up overwriting the already-hydrated SSR data everywhere that query key is used (not just in the header).
- Hard-reload it and check the Network tab: one extra client-side
-
/fixed— same layout, except the sharedHydrationBoundarywraps both the header and the page body, and owns the prefetch itself (i.e. state is provided at the nearest common ancestor of all consumers). Zero client-side fetches, every time. -
/broken-suspense— same as/broken, but the header usesuseSuspenseQueryinstead ofuseQuery(wrapped in its own<Suspense>). This is a distinct failure mode: no client-side network request is made at all, but the server terminal shows the shared query resolved twice during a single SSR pass (once for the header's ownfetchOptimistic()during render, once for the page'sprefetchQuery()), and the browser throws a real hydration-mismatch error, discarding and re-rendering the whole subtree client-side.
/broken and /broken-suspense reproduce reliably (observed on every
hard reload in next dev and in next build && next start) because the
layout that owns the header has no await before its own dehydrate()
call, so it always finishes before the 400ms-delayed page prefetch — this
removes the run-to-run non-determinism you'd see in a real app where both
the outer and inner boundaries do comparable amounts of async work.