renderToReadableStream·续
You can further nest <Suspense> boundaries to create a more granular loading sequence:
```js {5,13}
function ProfilePage() {
return (
In this example, React can start streaming the page even earlier. Only `ProfileLayout` and `ProfileCover` must finish rendering first because they are not wrapped in any `<Suspense>` boundary. However, if `Sidebar`, `Friends`, or `Photos` need to load some data, React will send the HTML for the `BigSpinner` fallback instead. Then, as more data becomes available, more content will continue to be revealed until all of it becomes visible.
Streaming does not need to wait for React itself to load in the browser, or for your app to become interactive. The HTML content from the server will get progressively revealed before any of the `<script>` tags load.
[Read more about how streaming HTML works.](https://github.com/reactwg/react-18/discussions/37)
> [!NOTE]
>
> Only data read from a source that [activates a Suspense boundary](/reference/react/Suspense#what-activates-a-suspense-boundary), such as a Promise read with [`use`](/reference/react/use), will suspend during rendering. Suspense does not detect data fetched inside an Effect or event handler.
>
---
### Specifying what goes into the shell
The part of your app outside of any `<Suspense>` boundaries is called *the shell:*
```js {3-5,13,14}
function ProfilePage() {
return (
<ProfileLayout>
<ProfileCover />
<Suspense fallback={<BigSpinner />}>
<Sidebar>
<Friends />
<Photos />
</Sidebar>
<Suspense fallback={<PostsGlimmer />}>
<Posts />
</Suspense>
</Suspense>
</ProfileLayout>
);
}
It determines the earliest loading state that the user may see:
```js {3-5,13
If you wrap the whole app into a `<Suspense>` boundary at the root, the shell will only contain that spinner. However, that's not a pleasant user experience because seeing a big spinner on the screen can feel slower and more annoying than waiting a bit more and seeing the real layout. This is why usually you'll want to place the `<Suspense>` boundaries so that the shell feels *minimal but complete*--like a skeleton of the entire page layout.
The async call to `renderToReadableStream` will resolve to a `stream` as soon as the entire shell has been rendered. Usually, you'll start streaming then by creating and returning a response with that `stream`:
```js {5}
async function handler(request) {
const stream = await renderToReadableStream(<App />, {
bootstrapScripts: ['/main.js']
});
return new Response(stream, {
headers: { 'content-type': 'text/html' },
});
}
By the time the stream is returned, components in nested <Suspense> boundaries might still be loading data.
Logging crashes on the server
By default, all errors on the server are logged to console. You can override this behavior to log crash reports:
```js {4-7}
async function handler(request) {
const stream = await renderToReadableStream(
If you provide a custom `onError` implementation, don't forget to also log errors to the console like above.
---
### Recovering from errors inside the shell
In this example, the shell contains `ProfileLayout`, `ProfileCover`, and `PostsGlimmer`:
```js {3-5,7-8}
function ProfilePage() {
return (
<ProfileLayout>
<ProfileCover />
<Suspense fallback={<PostsGlimmer />}>
<Posts />
</Suspense>
</ProfileLayout>
);
}
If an error occurs while rendering those components, React won't have any meaningful HTML to send to the client. Wrap your renderToReadableStream call in a try...catch to send a fallback HTML that doesn't rely on server rendering as the last resort:
```js {2,13-18}
async function handler(request) {
try {
const stream = await renderToReadableStream(
Something went wrong
', { status: 500, headers: { 'content-type': 'text/html' }, }); } }
If there is an error while generating the shell, both `onError` and your `catch` block will fire. Use `onError` for error reporting and use the `catch` block to send the fallback HTML document. Your fallback HTML does not have to be an error page. Instead, you may include an alternative shell that renders your app on the client only.
---
### Recovering from errors outside the shell
In this example, the `<Posts />` component is wrapped in `<Suspense>` so it is *not* a part of the shell:
```js {6}
function ProfilePage() {
return (
<ProfileLayout>
<ProfileCover />
<Suspense fallback={<PostsGlimmer />}>
<Posts />
</Suspense>
</ProfileLayout>
);
}
If an error happens in the Posts component or somewhere inside it, React will try to recover from it:
- It will emit the loading fallback for the closest
<Suspense>boundary (PostsGlimmer) into the HTML. - It will "give up" on trying to render the
Postscontent on the server anymore. - When the JavaScript code loads on the client, React will retry rendering
Postson the client.
If retrying rendering Posts on the client also fails, React will throw the error on the client. As with all the errors thrown during rendering, the closest parent error boundary determines how to present the error to the user. In practice, this means that the user will see a loading indicator until it is certain that the error is not recoverable.
If retrying rendering Posts on the client succeeds, the loading fallback from the server will be replaced with the client rendering output. The user will not know that there was a server error. However, the server onError callback and the client onRecoverableError callbacks will fire so that you can get notified about the error.
Setting the status code
Streaming introduces a tradeoff. You want to start streaming the page as early as possible so that the user can see the content sooner. However, once you start streaming, you can no longer set the response status code.
By dividing your app into the shell (above all <Suspense> boundaries) and the rest of the content, you've already solved a part of this problem. If the shell errors, your catch block will run which lets you set the error status code. Otherwise, you know that the app may recover on the client, so you can send "OK".
```js {11}
async function handler(request) {
try {
const stream = await renderToReadableStream(
Something went wrong
', { status: 500, headers: { 'content-type': 'text/html' }, }); } }
If a component *outside* the shell (i.e. inside a `<Suspense>` boundary) throws an error, React will not stop rendering. This means that the `onError` callback will fire, but your code will continue running without getting into the `catch` block. This is because React will try to recover from that error on the client, [as described above.](#recovering-from-errors-outside-the-shell)
However, if you'd like, you can use the fact that something has errored to set the status code:
```js {3,7,13}
async function handler(request) {
try {
let didError = false;
const stream = await renderToReadableStream(<App />, {
bootstrapScripts: ['/main.js'],
onError(error) {
didError = true;
console.error(error);
logServerCrashReport(error);
}
});
return new Response(stream, {
status: didError ? 500 : 200,
headers: { 'content-type': 'text/html' },
});
} catch (error) {
return new Response('<h1>Something went wrong</h1>', {
status: 500,
headers: { 'content-type': 'text/html' },
});
}
}
This will only catch errors outside the shell that happened while generating the initial shell content, so it's not exhaustive. If knowing whether an error occurred for some content is critical, you can move it up into the shell.
Handling different errors in different ways
You can create your own Error subclasses and use the instanceof operator to check which error is thrown. For example, you can define a custom NotFoundError and throw it from your component. Then you can save the error in onError and do something different before returning the response depending on the error type:
```js {2-3,5-15,22,28,33} async function handler(request) { let didError = false; let caughtError = null;
function getStatusCode() { if (didError) { if (caughtError instanceof NotFoundError) { return 404; } else { return 500; } } else { return 200; } }
try {
const stream = await renderToReadableStream(
Something went wrong
', { status: getStatusCode(), headers: { 'content-type': 'text/html' }, }); } }
Keep in mind that once you emit the shell and start streaming, you can't change the status code.
---
### Waiting for all content to load for crawlers and static generation
Streaming offers a better user experience because the user can see the content as it becomes available.
However, when a crawler visits your page, or if you're generating the pages at the build time, you might want to let all of the content load first and then produce the final HTML output instead of revealing it progressively.
You can wait for all the content to load by awaiting the `stream.allReady` Promise:
```js {12-15}
async function handler(request) {
try {
let didError = false;
const stream = await renderToReadableStream(<App />, {
bootstrapScripts: ['/main.js'],
onError(error) {
didError = true;
console.error(error);
logServerCrashReport(error);
}
});
let isCrawler = // ... depends on your bot detection strategy ...
if (isCrawler) {
await stream.allReady;
}
return new Response(stream, {
status: didError ? 500 : 200,
headers: { 'content-type': 'text/html' },
});
} catch (error) {
return new Response('<h1>Something went wrong</h1>', {
status: 500,
headers: { 'content-type': 'text/html' },
});
}
}
A regular visitor will get a stream of progressively loaded content. A crawler will receive the final HTML output after all the data loads. However, this also means that the crawler will have to wait for all data, some of which might be slow to load or error. Depending on your app, you could choose to send the shell to the crawlers too.
Aborting server rendering
You can force the server rendering to "give up" after a timeout:
```js {3,4-6,9} async function handler(request) { try { const controller = new AbortController(); setTimeout(() => { controller.abort(); }, 10000);
const stream = await renderToReadableStream(
React will flush the remaining loading fallbacks as HTML, and will attempt to render the rest on the client.
