-
-
Notifications
You must be signed in to change notification settings - Fork 238
Expand file tree
/
Copy pathentry.ssr.tsx
More file actions
74 lines (69 loc) · 2.54 KB
/
entry.ssr.tsx
File metadata and controls
74 lines (69 loc) · 2.54 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { createFromReadableStream } from '@vitejs/plugin-rsc/ssr'
import React from 'react'
import type { ReactFormState } from 'react-dom/client'
import { renderToReadableStream } 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
},
): Promise<{ stream: ReadableStream<Uint8Array>; status?: number }> {
// 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> | undefined
function SsrRoot() {
// deserialization needs to be kicked off inside ReactDOMServer context
// for ReactDomServer preinit/preloading to work
payload ??= createFromReadableStream<RscPayload>(rscStream1)
return React.use(payload).root
}
// render html (traditional SSR)
const bootstrapScriptContent =
await import.meta.viteRsc.loadBootstrapScriptContent('index')
let htmlStream: ReadableStream<Uint8Array>
let status: number | undefined
try {
htmlStream = await renderToReadableStream(<SsrRoot />, {
bootstrapScriptContent: options?.debugNojs
? undefined
: bootstrapScriptContent,
nonce: options?.nonce,
formState: options?.formState,
})
} catch (e) {
// fallback to render an empty shell and run pure CSR on browser,
// which can replay server component error and trigger error boundary.
status = 500
htmlStream = await renderToReadableStream(
<html>
<body>
<noscript>Internal Server Error: SSR failed</noscript>
</body>
</html>,
{
bootstrapScriptContent:
`self.__NO_HYDRATE=1;` +
(options?.debugNojs ? '' : bootstrapScriptContent),
nonce: options?.nonce,
},
)
}
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 { stream: responseStream, status }
}