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

renderRouterToStream.tsx

83 lines2.4 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 progressiveChunkSize: Number.POSITIVE_INFINITY,
28 })
29​
30 if (isbot(request.headers.get('User-Agent'))) {
31 await stream.allReady
32 }
33​
34 const responseStream = transformReadableStreamWithRouter(
35 router,
36 stream as unknown as ReadableStream,
37 )
38 return new Response(responseStream as any, {
39 status: router.state.statusCode,
40 headers: responseHeaders,
41 })
42 }
43​
44 if (typeof ReactDOMServer.renderToPipeableStream === 'function') {
45 const reactAppPassthrough = new PassThrough()
46​
47 try {
48 const pipeable = ReactDOMServer.renderToPipeableStream(children, {
49 nonce: router.options.ssr?.nonce,
50 progressiveChunkSize: Number.POSITIVE_INFINITY,
51 ...(isbot(request.headers.get('User-Agent'))
52 ? {
53 onAllReady() {
54 pipeable.pipe(reactAppPassthrough)
55 },
56 }
57 : {
58 onShellReady() {
59 pipeable.pipe(reactAppPassthrough)
60 },
61 }),
62 onError: (error, info) => {
63 console.error('Error in renderToPipeableStream:', error, info)
64 },
65 })
66 } catch (e) {
67 console.error('Error in renderToPipeableStream:', e)
68 }
69​
70 const responseStream = transformPipeableStreamWithRouter(
71 router,
72 reactAppPassthrough,
73 )
74 return new Response(responseStream as any, {
75 status: router.state.statusCode,
76 headers: responseHeaders,
77 })
78 }
79​
80 throw new Error(
81 'No renderToReadableStream or renderToPipeableStream found in react-dom/server. Ensure you are using a version of react-dom that supports streaming.',
82 )