Skip to content

Commit 7fe3922

Browse files
committed
chore(rsc): update example to fallback to CSR on SSR error
1 parent 49fbfa7 commit 7fe3922

File tree

2 files changed

+34
-13
lines changed

2 files changed

+34
-13
lines changed

packages/plugin-rsc/examples/basic/src/framework/entry.browser.tsx

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import {
66
encodeReply,
77
} from '@vitejs/plugin-rsc/browser'
88
import React from 'react'
9-
import { hydrateRoot } from 'react-dom/client'
9+
import { createRoot, hydrateRoot } from 'react-dom/client'
1010
import { rscStream } from 'rsc-html-stream/client'
1111
import type { RscPayload } from './entry.rsc'
1212
import { GlobalErrorBoundary } from './error-boundary'
@@ -75,9 +75,13 @@ async function main() {
7575
</GlobalErrorBoundary>
7676
</React.StrictMode>
7777
)
78-
hydrateRoot(document, browserRoot, {
79-
formState: initialPayload.formState,
80-
})
78+
if ('__NO_HYDRATE' in globalThis) {
79+
createRoot(document).render(browserRoot)
80+
} else {
81+
hydrateRoot(document, browserRoot, {
82+
formState: initialPayload.formState,
83+
})
84+
}
8185

8286
// implement server HMR by trigering re-fetch/render of RSC upon server code change
8387
if (import.meta.hot) {

packages/plugin-rsc/examples/basic/src/framework/entry.ssr.tsx

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,15 +28,32 @@ export async function renderHTML(
2828
}
2929

3030
// render html (traditional SSR)
31-
const bootstrapScriptContent =
32-
await import.meta.viteRsc.loadBootstrapScriptContent('index')
33-
const htmlStream = await renderToReadableStream(<SsrRoot />, {
34-
bootstrapScriptContent: options?.debugNojs
35-
? undefined
36-
: bootstrapScriptContent,
37-
nonce: options?.nonce,
38-
formState: options?.formState,
39-
})
31+
const bootstrapScriptContent = options?.debugNojs
32+
? undefined
33+
: await import.meta.viteRsc.loadBootstrapScriptContent('index')
34+
35+
let htmlStream: ReadableStream<Uint8Array>
36+
try {
37+
htmlStream = await renderToReadableStream(<SsrRoot />, {
38+
bootstrapScriptContent: options?.debugNojs
39+
? undefined
40+
: bootstrapScriptContent,
41+
nonce: options?.nonce,
42+
formState: options?.formState,
43+
})
44+
} catch (e) {
45+
// fallback to render an empty shell and run pure CSR on browser,
46+
// which replays server component error via error boundary.
47+
htmlStream = await renderToReadableStream(
48+
<html>
49+
<body></body>
50+
</html>,
51+
{
52+
bootstrapScriptContent: `self.__NO_HYDRATE=1;` + bootstrapScriptContent,
53+
nonce: options?.nonce,
54+
},
55+
)
56+
}
4057

4158
let responseStream: ReadableStream<Uint8Array> = htmlStream
4259
if (!options?.debugNojs) {

0 commit comments

Comments
 (0)