-
-
Notifications
You must be signed in to change notification settings - Fork 249
Expand file tree
/
Copy pathentry.ssr.tsx
More file actions
57 lines (52 loc) · 1.99 KB
/
entry.ssr.tsx
File metadata and controls
57 lines (52 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { injectRscStreamToHtml } from '@vitejs/plugin-rsc/rsc-html-stream/ssr' // helper API
import * as ReactClient from '@vitejs/plugin-rsc/ssr' // RSC API
import React from 'react'
import type { ReactFormState } from 'react-dom/client'
import * as ReactDOMServer from 'react-dom/server.edge'
import type { RscPayload } from './entry.rsc'
export async function renderHTML(
rscStream: ReadableStream<Uint8Array>,
options: {
formState?: ReactFormState
nonce?: string
debugNojs?: boolean
},
) {
// duplicate one RSC stream into two.
// - one for SSR (ReactClient.createFromReadableStream below)
// - another for browser hydration payload by injecting <script>...FLIGHT_DATA...</script>.
const [rscStream1, rscStream2] = rscStream.tee()
// deserialize RSC stream back to React VDOM
let payload: Promise<RscPayload>
function SsrRoot() {
// deserialization needs to be kicked off inside ReactDOMServer context
// for ReactDomServer preinit/preloading to work
payload ??= ReactClient.createFromReadableStream<RscPayload>(rscStream1)
return React.use(payload).root
}
// render html (traditional SSR)
const bootstrapScriptContent =
await import.meta.viteRsc.loadBootstrapScriptContent('index')
const htmlStream = await ReactDOMServer.renderToReadableStream(<SsrRoot />, {
bootstrapScriptContent: options?.debugNojs
? undefined
: bootstrapScriptContent,
nonce: options?.nonce,
// signal: undefined,
// no types
...{ formState: options?.formState },
})
let responseStream: ReadableStream<Uint8Array> = htmlStream
if (!options?.debugNojs) {
console.log('[responseStream.pipeThrough:before]')
// initial RSC stream is injected in HTML stream as <script>...FLIGHT_DATA...</script>
responseStream = responseStream.pipeThrough(
injectRscStreamToHtml(rscStream2, {
nonce: options?.nonce,
}),
)
console.log('[responseStream.pipeThrough:after]')
// responseStream.cancel()
}
return responseStream
}