Skip to content

Commit 7edb8b3

Browse files
committed
fix(react-router): avoid suspense above root documents
1 parent 3848503 commit 7edb8b3

5 files changed

Lines changed: 97 additions & 18 deletions

File tree

‎.changeset/fresh-ducks-hydrate.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/react-router': patch
3+
---
4+
5+
Avoid wrapping root components that may render the HTML document in a Suspense boundary during SSR and hydration.

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

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,15 @@ const outletMatchSelectionEqual = (
4848
b: OutletMatchSelection,
4949
) => a[0] === b[0] && a[1] === b[1]
5050

51+
function canWrapRouteInSuspense(route: AnyRoute, resolvedNoSsr: boolean) {
52+
return (
53+
!route.isRoot ||
54+
!!(route.options as RootRouteOptions).shellComponent ||
55+
!!route.options.wrapInSuspense ||
56+
resolvedNoSsr
57+
)
58+
}
59+
5160
export const Match = React.memo(function MatchImpl({
5261
routeId,
5362
}: {
@@ -89,10 +98,14 @@ function MatchView({
8998
: route.options.notFoundComponent
9099

91100
const resolvedNoSsr = match.ssr === false || match.ssr === 'data-only'
101+
// A root component may render the document itself. Only place its Suspense
102+
// boundary inside an explicit shell, unless the route forcefully opts in.
103+
const canWrapInSuspense = canWrapRouteInSuspense(route, resolvedNoSsr)
92104
const ResolvedSuspenseBoundary =
105+
canWrapInSuspense &&
93106
(route.options.wrapInSuspense ??
94-
pendingElement ??
95-
((route.options.errorComponent as any)?.preload || resolvedNoSsr))
107+
pendingElement ??
108+
((route.options.errorComponent as any)?.preload || resolvedNoSsr))
96109
? React.Suspense
97110
: SafeFragment
98111

@@ -198,6 +211,13 @@ export const MatchInner = React.memo(function MatchInnerImpl({
198211
}, [key, route.options.component, router.options.defaultComponent])
199212

200213
if (match.status === 'pending') {
214+
const resolvedNoSsr = match.ssr === false || match.ssr === 'data-only'
215+
if (!canWrapRouteInSuspense(route, resolvedNoSsr)) {
216+
// Replacing an SSR document root with pending UI would remove <html>.
217+
// Hydrated matches retain their prior data, so keep rendering it while
218+
// pure CSR roots can safely render the pending element directly.
219+
return router.ssr ? out : renderPending(router, route)
220+
}
201221
if (router._tx) {
202222
throw router._tx[5]
203223
}

‎packages/react-router/tests/issue-7986-retained-pending.test.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -480,7 +480,7 @@ test('a global not-found destination does not retain the mounted root success',
480480
})
481481

482482
expect(await screen.findByTestId('pending')).toBeVisible()
483-
expect(screen.getByTestId('content')).not.toBeVisible()
483+
expect(screen.queryByTestId('content')).not.toBeInTheDocument()
484484

485485
await act(async () => {
486486
missingLoader.resolve()
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import { expect, test } from 'vitest'
2+
import { Outlet, createRootRoute, createRoute, createRouter } from '../src'
3+
import {
4+
RouterServer,
5+
createRequestHandler,
6+
renderRouterToStream,
7+
} from '../src/ssr/server'
8+
9+
// https://github.com/TanStack/router/issues/8053
10+
test('a root pendingComponent does not wrap the SSR document in Suspense', async () => {
11+
const rootRoute = createRootRoute({
12+
pendingComponent: () => null,
13+
component: () => (
14+
<html>
15+
<head>
16+
<title>Root document</title>
17+
</head>
18+
<body>
19+
<Outlet />
20+
</body>
21+
</html>
22+
),
23+
})
24+
const indexRoute = createRoute({
25+
getParentRoute: () => rootRoute,
26+
path: '/',
27+
component: () => <main>Root content</main>,
28+
})
29+
const handler = createRequestHandler({
30+
request: new Request('http://localhost/'),
31+
createRouter: () =>
32+
createRouter({
33+
routeTree: rootRoute.addChildren([indexRoute]),
34+
isServer: true,
35+
}),
36+
})
37+
38+
const response = await handler(({ request, router, responseHeaders }) =>
39+
renderRouterToStream({
40+
request,
41+
router,
42+
responseHeaders,
43+
children: <RouterServer router={router} />,
44+
}),
45+
)
46+
const html = await response.text()
47+
const serverDocument = new DOMParser().parseFromString(html, 'text/html')
48+
49+
expect(response.status).toBe(200)
50+
expect(serverDocument.body.textContent).toContain('Root content')
51+
expect(html).not.toContain('<!--html--><!--head--><!--body-->')
52+
})

‎packages/react-router/tests/root-pending-min.test.tsx‎

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,8 @@ test('a post-hydration root reload keeps its fallback through pendingMinMs', asy
8484
})
8585

8686
expect(rootLoader).toHaveBeenCalledTimes(1)
87-
expect(screen.getByTestId('root-pending')).toBeInTheDocument()
88-
expect(screen.getByTestId('root-content')).not.toBeVisible()
87+
expect(screen.queryByTestId('root-pending')).not.toBeInTheDocument()
88+
expect(screen.getByTestId('root-content')).toHaveTextContent('Generation 1')
8989

9090
await act(async () => {
9191
reloadGate.resolve()
@@ -95,7 +95,7 @@ test('a post-hydration root reload keeps its fallback through pendingMinMs', asy
9595
await act(async () => {
9696
await vi.advanceTimersByTimeAsync(99)
9797
})
98-
expect(screen.getByTestId('root-pending')).toBeInTheDocument()
98+
expect(screen.queryByTestId('root-pending')).not.toBeInTheDocument()
9999

100100
await act(async () => {
101101
await vi.advanceTimersByTimeAsync(1)
@@ -105,7 +105,7 @@ test('a post-hydration root reload keeps its fallback through pendingMinMs', asy
105105
expect(screen.getByTestId('root-content')).toHaveTextContent('Generation 2')
106106
})
107107

108-
test('root route hydration preserves component state across its Suspense boundary', async () => {
108+
test('root route hydration without a pending boundary preserves component state', async () => {
109109
const mounts = vi.fn()
110110
const unmounts = vi.fn()
111111
const initializers = vi.fn(() => 'preserved')
@@ -127,14 +127,13 @@ test('root route hydration preserves component state across its Suspense boundar
127127
})
128128
await router.load()
129129

130-
// Model the server render and the client router produced by hydrate(). The
131-
// outer root boundary is intentionally absent from both trees, while the
132-
// route's own pending boundary is present in both.
130+
// Model the server render and the client router produced by hydrate(). A root
131+
// without a separate shell stays unwrapped on both sides of hydration.
133132
router.ssr = { manifest: { routes: {} } }
134133
router.isServer = true
135134
const html = renderToString(<RouterProvider router={router} />)
136135
router.isServer = false
137-
expect(html).toContain('<!--$-->')
136+
expect(html).not.toContain('<!--$-->')
138137
expect(html).toContain('preserved')
139138

140139
const container = document.createElement('div')
@@ -153,19 +152,23 @@ test('root route hydration preserves component state across its Suspense boundar
153152
})
154153

155154
expect(container).toHaveTextContent('preserved')
156-
// One initializer belongs to the server render and one to client
157-
// hydration. The stable boundary must preserve that hydrated client
158-
// instance instead of creating a third one.
155+
// One initializer belongs to the server render and one to client hydration.
159156
expect(initializers).toHaveBeenCalledTimes(2)
160157
expect(mounts).toHaveBeenCalledTimes(1)
161158
expect(unmounts).not.toHaveBeenCalled()
162159
expect(consoleError).not.toHaveBeenCalled()
163160
})
164161

165-
test('server rendering uses the root pending boundary for route component suspension', async () => {
162+
test('server rendering uses the root pending boundary inside its document shell', async () => {
166163
const gate = createControlledPromise<void>()
167164
const rootRoute = createRootRoute({
168165
pendingComponent: () => <div>Server root pending</div>,
166+
shellComponent: ({ children }) => (
167+
<html>
168+
<head />
169+
<body>{children}</body>
170+
</html>
171+
),
169172
component: () => {
170173
throw gate
171174
},
@@ -179,8 +182,7 @@ test('server rendering uses the root pending boundary for route component suspen
179182

180183
const html = renderToString(<RouterProvider router={router} />)
181184

182-
// renderToString cannot wait for Suspense, but the root route's stable
183-
// boundary contains the suspension and emits its fallback. Streaming SSR
184-
// can wait for the same boundary instead.
185+
// renderToString cannot wait for Suspense, but the boundary inside the root
186+
// shell contains the suspension and emits its fallback.
185187
expect(html).toContain('Server root pending')
186188
})

0 commit comments

Comments
 (0)