Open History to see the last commit
1import { Suspense } from 'react'
2import { afterEach, describe, expect, test, vi } from 'vitest'
3import { attachRouterServerSsrUtils } from '@tanstack/router-core/ssr/server'
4import {
5 RouterContextProvider,
6 Scripts,
7 createMemoryHistory,
8 createRootRoute,
9 createRouter,
10} from '../src'
11import type * as ReactDOMServer from 'react-dom/server'
12import type { AnyRouter } from '@tanstack/router-core'
13β
14/**
15 * Load the adapter against the real React 19 renderer. Node's `react-dom`
16 * exports both entry points; hiding `renderToReadableStream` exercises the
17 * pipeable path that every Node user on React < 19.2 runs.
18 */
19async function loadRenderRouterToStream(path: 'readable' | 'pipeable') {
20 vi.resetModules()
21 if (path === 'pipeable') {
22 vi.doMock('react-dom/server', async (importOriginal) => {
23 // The runtime module is CommonJS, so its interop `default` is the namespace.
24 const actual = await importOriginal<{ default: typeof ReactDOMServer }>()
25 return {
26 ...actual,
27 default: { ...actual.default, renderToReadableStream: undefined },
28 }
29 })
30 } else {
31 vi.doUnmock('react-dom/server')
32 }
33 const reactDomServer = (await import('react-dom/server')).default
34 const renderToPipeableStream = vi.spyOn(
35 reactDomServer,
36 'renderToPipeableStream',
37 )
38 const { renderRouterToStream } =
39 await import('../src/ssr/renderRouterToStream')
40 return { renderRouterToStream, renderToPipeableStream }
41}
42β
43const activeRouters: Array<AnyRouter> = []
44β
45afterEach(() => {
46 for (const router of activeRouters.splice(0)) {
47 router.serverSsr?.cleanup()
48 }
49})
50β
51async function buildRouter(dehydratedData: { routerData: Promise<string> }) {
52 const rootRoute = createRootRoute({ component: () => null })
53 const router = createRouter({
54 history: createMemoryHistory({ initialEntries: ['/'] }),
55 routeTree: rootRoute,
56 dehydrate: () => dehydratedData,
57 })
58 activeRouters.push(router)
59 router.isServer = true
60 attachRouterServerSsrUtils({ router, manifest: undefined })
61 await router.load()
62 await router.serverSsr!.dehydrate()
63 return router
64}
65β
66function createSuspendingComponent(id: string, text: string) {
67 let ready = false
68 let resolve!: () => void
69 const pending = new Promise<void>((done) => {
70 resolve = () => {
71 ready = true
72 done()
73 }
74 })
75β
76 return {
77 Component() {
78 if (!ready) {
79 throw pending
80 }
81 return <div id={id}>{text}</div>
82 },
83 resolve,
84 }
85}
86β
87async function readWithTimeout(
88 reader: ReadableStreamDefaultReader<Uint8Array>,
89) {
90 let timeout: ReturnType<typeof setTimeout> | undefined
91 try {
92 return await Promise.race([
93 reader.read(),
94 new Promise<never>((_resolve, reject) => {
95 timeout = setTimeout(
96 () => reject(new Error('Timed out waiting for React SSR output')),
97 2000,
98 )
99 }),
100 ])
101 } finally {
102 if (timeout) {
103 clearTimeout(timeout)
104 }
105 }
106}
107β
108async function readUntil(
109 reader: ReadableStreamDefaultReader<Uint8Array>,
110 decoder: TextDecoder,
111 state: { html: string },
112 condition: (html: string) => boolean,
113) {
114 while (!condition(state.html)) {
115 const { done, value } = await readWithTimeout(reader)
116 if (done) {
117 throw new Error('React SSR response ended before the expected output')
118 }
119 state.html += decoder.decode(value, { stream: true })
120 }
121}
122β
123describe.each(['readable', 'pipeable'] as const)(
124 'renderRouterToStream - real React 19 renderer (%s)',
125 (path) => {
126 test('emits router data after a real Suspense patch while React is still rendering', async () => {
127 const { renderRouterToStream, renderToPipeableStream } =
128 await loadRenderRouterToStream(path)
129 let resolveRouterData!: (value: string) => void
130 const routerData = new Promise<string>((resolve) => {
131 resolveRouterData = resolve
132 })
133 const router = await buildRouter({ routerData })
134 const first = createSuspendingComponent('first-result', 'first-resolved')
135 const second = createSuspendingComponent(
136 'second-result',
137 'second-resolved',
138 )
139 const requestController = new AbortController()
140β
141 const { response } = await renderRouterToStream({
142 request: new Request('http://localhost/', {
143 signal: requestController.signal,
144 }),
145 router,
146 responseHeaders: new Headers(),
147 children: (
148 <html>
149 <body>
150 <RouterContextProvider router={router}>
151 <Suspense fallback={<p>first-fallback</p>}>
152 <first.Component />
153 </Suspense>
154 <Suspense fallback={<p>second-fallback</p>}>
155 <second.Component />
156 </Suspense>
157 <Scripts />
158 </RouterContextProvider>
159 </body>
160 </html>
161 ),
162 })
163 const reader = response.body!.getReader()
164 const decoder = new TextDecoder()
165 const state = { html: '' }
166β
167 try {
168 // The shell ends with <Scripts />, whose last child is the boundary.
169 await readUntil(reader, decoder, state, (html) => {
170 const shell = html.indexOf('second-fallback')
171 return shell >= 0 && html.indexOf('</script>', shell) >= 0
172 })
173 expect(state.html).toContain('first-fallback')
174β
175 first.resolve()
176 await readUntil(reader, decoder, state, (html) => {
177 const result = html.indexOf('first-resolved')
178 return result >= 0 && html.indexOf('</script>', result) >= 0
179 })
180β
181 const firstResult = state.html.indexOf('first-resolved')
182 const reactPatchEnd =
183 state.html.indexOf('</script>', firstResult) + '</script>'.length
184 const reactPatch = state.html.slice(firstResult, reactPatchEnd)
185 expect(reactPatch).toContain('<script')
186 expect(reactPatch.endsWith('</script>')).toBe(true)
187 expect(state.html).not.toContain('second-resolved')
188 expect(state.html).not.toContain('</body></html>')
189β
190 resolveRouterData('late-react19-router-value')
191 await readUntil(reader, decoder, state, (html) =>
192 html.includes('late-react19-router-value'),
193 )
194β
195 // The second Suspense boundary still keeps React's renderer open. The
196 // router batch can therefore only have used React's completed patch
197 // script as its insertion point.
198 const routerValue = state.html.indexOf('late-react19-router-value')
199 expect(routerValue).toBeGreaterThan(reactPatchEnd)
200 expect(state.html).not.toContain('second-resolved')
201 expect(state.html).not.toContain('</body></html>')
202β
203 second.resolve()
204 for (;;) {
205 const { done, value } = await readWithTimeout(reader)
206 if (done) {
207 break
208 }
209 state.html += decoder.decode(value, { stream: true })
210 }
211 state.html += decoder.decode()
212β
213 expect(state.html).toContain('second-resolved')
214 expect(state.html.endsWith('</body></html>')).toBe(true)
215 expect(router.serverSsr).toBeUndefined()
216 expect(renderToPipeableStream).toHaveBeenCalledTimes(
217 path === 'pipeable' ? 1 : 0,
218 )
219 } finally {
220 first.resolve()
221 second.resolve()
222 requestController.abort(new Error('test-complete'))
223 await reader.cancel().catch(() => {})
224 }
225 })
226 },
227)