-
-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathentry.ssr.tsx
More file actions
54 lines (49 loc) · 1.87 KB
/
Copy pathentry.ssr.tsx
File metadata and controls
54 lines (49 loc) · 1.87 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
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 { injectRSCPayload } from 'rsc-html-stream/server'
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,
// no types
...{ formState: options?.formState },
})
let responseStream: ReadableStream<Uint8Array> = htmlStream
if (!options?.debugNojs) {
// initial RSC stream is injected in HTML stream as <script>...FLIGHT_DATA...</script>
// using utility made by devongovett https://github.com/devongovett/rsc-html-stream
responseStream = responseStream.pipeThrough(
injectRSCPayload(rscStream2, {
nonce: options?.nonce,
}),
)
}
return responseStream
}