Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

renderRouterToStream.tsx

81 lines2.3 KB

1import { PassThrough } from 'node:stream'
2import ReactDOMServer from 'react-dom/server'
3import { isbot } from 'isbot'
4import {
5 transformPipeableStreamWithRouter,
6 transformReadableStreamWithRouter,
7} from '@tanstack/router-core/ssr/server'
8import type { AnyRouter } from '@tanstack/router-core'
9import type { ReadableStream } from 'node:stream/web'
10import type { ReactNode } from 'react'
11​
12export const renderRouterToStream = async ({
13 request,
14 router,
15 responseHeaders,
16 children,
17}: {
18 request: Request
19 router: AnyRouter
20 responseHeaders: Headers
21 children: ReactNode
22}) => {
23 if (typeof ReactDOMServer.renderToReadableStream === 'function') {
24 const stream = await ReactDOMServer.renderToReadableStream(children, {
25 signal: request.signal,
26 nonce: router.options.ssr?.nonce,
27 })
28​
29 if (isbot(request.headers.get('User-Agent'))) {
30 await stream.allReady
31 }
32​
33 const responseStream = transformReadableStreamWithRouter(
34 router,
35 stream as unknown as ReadableStream,
36 )
37 return new Response(responseStream as any, {
38 status: router.state.statusCode,
39 headers: responseHeaders,
40 })
41 }
42​
43 if (typeof ReactDOMServer.renderToPipeableStream === 'function') {
44 const reactAppPassthrough = new PassThrough()
45​
46 try {
47 const pipeable = ReactDOMServer.renderToPipeableStream(children, {
48 nonce: router.options.ssr?.nonce,
49 ...(isbot(request.headers.get('User-Agent'))
50 ? {
51 onAllReady() {
52 pipeable.pipe(reactAppPassthrough)
53 },
54 }
55 : {
56 onShellReady() {
57 pipeable.pipe(reactAppPassthrough)
58 },
59 }),
60 onError: (error, info) => {
61 console.error('Error in renderToPipeableStream:', error, info)
62 },
63 })
64 } catch (e) {
65 console.error('Error in renderToPipeableStream:', e)
66 }
67​
68 const responseStream = transformPipeableStreamWithRouter(
69 router,
70 reactAppPassthrough,
71 )
72 return new Response(responseStream as any, {
73 status: router.state.statusCode,
74 headers: responseHeaders,
75 })
76 }
77​
78 throw new Error(
79 'No renderToReadableStream or renderToPipeableStream found in react-dom/server. Ensure you are using a version of react-dom that supports streaming.',
80 )