Skip to content

Commit fba7a18

Browse files
committed
fix(react-router): render the pending document root only when its beforeLoad context exists
The document-root pending exception keeps rendering the real component because pending UI would remove <html> and hydrated matches retain their prior data. An uncommitted hydrated root has no prior data: hydrate() only merges the dehydrated beforeLoad context (b) for committed matches, so an id-mismatched or stale root renders with every beforeLoad-provided context key missing (#8115's production symptom, still present with #8116). Track beforeLoad settlement on the client (__beforeLoadContext, mirroring load-server) and via the dehydrated b for committed hydration, and gate the document-root exception on it.
1 parent e9f63a6 commit fba7a18

3 files changed

Lines changed: 123 additions & 2 deletions

File tree

‎packages/react-router/src/Match.tsx‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -213,9 +213,17 @@ export const MatchInner = React.memo(function MatchInnerImpl({
213213
}, [key, route.options.component, router.options.defaultComponent])
214214

215215
if (match.status === 'pending') {
216-
if (router.ssr && !canWrapInSuspense(router, route, match.ssr)) {
216+
if (
217+
router.ssr &&
218+
!canWrapInSuspense(router, route, match.ssr) &&
219+
(!route.options.beforeLoad ||
220+
(match as { __beforeLoadContext?: Record<string, unknown> })
221+
.__beforeLoadContext !== undefined)
222+
) {
217223
// Replacing an SSR document root with pending UI would remove <html>.
218-
// Hydrated matches retain their prior data, so keep rendering it.
224+
// Hydrated matches retain their prior data, so keep rendering it — but
225+
// only when the data is actually there: a root whose beforeLoad has not
226+
// contributed yet would render with its context keys missing (#8115).
219227
return out
220228
}
221229
if (router._tx) {
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import { cleanup, render, screen } from '@testing-library/react'
2+
import { afterEach, describe, expect, test, vi } from 'vitest'
3+
import { hydrate } from '@tanstack/router-core/ssr/client'
4+
import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id'
5+
import {
6+
Outlet,
7+
RouterProvider,
8+
createMemoryHistory,
9+
createRootRoute,
10+
createRoute,
11+
createRouter,
12+
} from '../src'
13+
import type { AnyRouteMatch } from '@tanstack/router-core'
14+
import type { TsrSsrGlobal } from '@tanstack/router-core/ssr/client'
15+
16+
function bootstrap(
17+
matches: Array<{
18+
id: string
19+
status: AnyRouteMatch['status']
20+
ssr: AnyRouteMatch['ssr']
21+
data?: unknown
22+
beforeLoadContext?: unknown
23+
}>,
24+
): void {
25+
window.$_TSR = {
26+
router: {
27+
manifest: undefined,
28+
matches: matches.map(({ id, status, ssr, data, beforeLoadContext }) => ({
29+
i: dehydrateSsrMatchId(id),
30+
l: data,
31+
s: status,
32+
ssr,
33+
u: Date.now(),
34+
...(beforeLoadContext !== undefined ? { b: beforeLoadContext } : {}),
35+
})),
36+
},
37+
h: vi.fn(),
38+
e: vi.fn(),
39+
c: vi.fn(),
40+
p: vi.fn(),
41+
buffer: [],
42+
} as TsrSsrGlobal
43+
}
44+
45+
afterEach(() => {
46+
cleanup()
47+
delete window.$_TSR
48+
})
49+
50+
// The document root cannot be replaced by pending UI (it holds <html>), so a
51+
// pending root renders its real component (Match.tsx). Hydration only merges a
52+
// dehydrated match's beforeLoad context (`b`) for committed matches — an
53+
// uncommitted root (id mismatch between server and client, e.g. a URL rewrite
54+
// disagreement) therefore renders its real component with every
55+
// beforeLoad-provided context key missing. Production impact in #8115.
56+
describe('hydration beforeLoad context window', () => {
57+
test('an uncommitted hydrated document root never renders with its beforeLoad context stripped', async () => {
58+
const observed: Array<string> = []
59+
let releaseBeforeLoad!: () => void
60+
const beforeLoadGate = new Promise<void>((resolve) => {
61+
releaseBeforeLoad = resolve
62+
})
63+
const rootRoute = createRootRoute({
64+
beforeLoad: async () => {
65+
await beforeLoadGate
66+
return { locale: 'en' }
67+
},
68+
component: function Root() {
69+
observed.push(String(rootRoute.useRouteContext().locale))
70+
return <Outlet />
71+
},
72+
})
73+
const indexRoute = createRoute({
74+
getParentRoute: () => rootRoute,
75+
path: '/',
76+
component: () => <div>home</div>,
77+
})
78+
const router = createRouter({
79+
history: createMemoryHistory({ initialEntries: ['/'] }),
80+
routeTree: rootRoute.addChildren([indexRoute]),
81+
defaultPendingComponent: () => <div>pending</div>,
82+
defaultPendingMs: 15,
83+
defaultPendingMinMs: 0,
84+
})
85+
const matches = router.matchRoutes(router.state.location)
86+
bootstrap([
87+
// The server dehydrated a different root match id than the client
88+
// rebuilt (a rewrite/serialization disagreement), so commitment stops at
89+
// index 0 and the root's `b` is never merged.
90+
{
91+
id: `${matches[0]!.id}__server-skew`,
92+
status: 'success',
93+
ssr: true,
94+
beforeLoadContext: { locale: 'en' },
95+
},
96+
{ id: matches[1]!.id, status: 'success', ssr: true },
97+
])
98+
99+
// Render while hydration is still in flight (RouterProvider is public API
100+
// and does not require hydrate() to settle first). The document root cannot
101+
// be replaced by pending UI, so it renders its real component.
102+
const hydration = hydrate(router)
103+
render(<RouterProvider router={router} />)
104+
releaseBeforeLoad()
105+
await hydration
106+
await screen.findByText('home')
107+
108+
expect(observed.length).toBeGreaterThan(0)
109+
expect([...new Set(observed)]).toEqual(['en'])
110+
})
111+
})

‎packages/router-core/src/load-client.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -452,6 +452,7 @@ async function contextualize(
452452
releaseFlight(router, match)
453453
return [index, outcome]
454454
}
455+
match.__beforeLoadContext = result ?? {}
455456
match.context = {
456457
...context,
457458
...result,
@@ -2286,6 +2287,7 @@ export async function hydrate(router: AnyRouter): Promise<void> {
22862287
}
22872288
candidate.status = dehydrated.s
22882289
candidate.ssr = dehydrated.ssr
2290+
candidate.__beforeLoadContext = dehydrated.b ?? {}
22892291
route.options.ssr = candidate.ssr
22902292
candidate.updatedAt = dehydrated.u
22912293
candidate.error = dehydrated.e

0 commit comments

Comments
 (0)