Sub topic 13
Shell readiness, errors, and timeouts on the server
This chapter assumes you know how to call renderToPipeableStream in an Express route, and that you understand Suspense boundaries as streaming units. It covers when the server may start sending HTML, what to do when rendering fails, and how to stop a render that takes too long.
What the shell is
The shell is the part of the page outside every Suspense boundary. In this tree, the shell is the <main> element and the <h1>. The comments are not part of it:
export default function Page() {
return (
<main>
<h1>Article</h1>
<Suspense fallback={<p>Loading comments...</p>}>
<Comments />
</Suspense>
</main>
);
}When the shell finishes rendering, React has HTML it can send. Content inside a boundary that is still waiting is represented by its fallback. React streams the real content later and swaps it in.
The shell matters because the HTTP status code and headers go out before the first byte of the body. After you call pipe(res), you can no longer change the status. So you decide the status when the shell is ready or when it fails.
The lifecycle callbacks
renderToPipeableStream takes an options object with callbacks. Four of them cover this chapter.
| Callback | When it fires | Typical use |
|---|---|---|
| `onShellReady` | The shell has rendered. Boundaries may still be pending. | Set headers and status, then call `pipe(res)`. |
| `onShellError` | The shell failed to render. Nothing can be streamed. | Send a fallback error page with status 500. |
| `onAllReady` | The shell and every boundary have finished. | Serve crawlers or static output, where you want complete HTML. |
| `onError` | Any error, in the shell or inside a boundary. | Log it and record that something failed. |
onError fires for every error, including errors that React recovers from. An error inside a Suspense boundary does not stop the page. React sends the fallback and lets the client retry rendering that boundary. The server still tells you about it through onError.
A complete route
This is the route from the spine. It sets the status at the moment the shell is ready, and it handles a failed shell separately.
import express from 'express';
import { renderToPipeableStream } from 'react-dom/server';
import App from './App.js';
const app = express();
app.use('/static', express.static('dist'));
app.get('/', (req, res) => {
let didError = false;
const { pipe, abort } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/static/client.js'],
onShellReady() {
res.statusCode = didError ? 500 : 200;
res.setHeader('Content-Type', 'text/html');
pipe(res);
},
onShellError(error) {
console.error(error);
res.statusCode = 500;
res.setHeader('Content-Type', 'text/html');
res.send('<h1>Something went wrong</h1>');
},
onError(error) {
didError = true;
console.error(error);
}
});
setTimeout(() => abort(), 10000);
});
app.listen(3000);Read the route in order.
didErrorstarts asfalse. Each call toonErrorsets it totrueand logs the error.- If the shell renders,
onShellReadyruns. If an error was already reported by then, the status is 500. Otherwise it is 200. Thenpipe(res)starts the stream. - If the shell cannot render,
onShellErrorruns instead.pipeis never called, so you are free to send your own response. Here that is a small static error page. - After 10 seconds,
abort()stops the render.
The status code trade-off
A status of 200 or 500 set in onShellReady reflects only what happened before the shell was ready. An error that happens later, inside a boundary that streams in after you called pipe, cannot change the status. The response is already 200 by then.
This is a trade-off, not a bug. You get a fast first byte, and in return the status code is less precise. If a page needs an exact status for every failure, such as a crawler that must see a 404, you can wait for onAllReady before calling pipe. That gives up streaming for that route.
Errors inside a boundary
Suppose Comments throws during server rendering. React does the following:
- Calls
onErrorwith the error, so your route logs it and setsdidError. - Keeps the fallback (
Loading comments...) in the HTML for that boundary. - Streams the rest of the page normally.
- Lets the client try to render the boundary itself when it hydrates. If that works, the user sees the comments. If it fails again, the nearest error boundary on the client takes over.
So an in-stream server error is often invisible to the user. It is visible to you only if you log it. Always log in onError.
Timeouts and abort
A slow data source can leave a boundary pending forever. Without a limit, the response never completes, and the connection and server memory stay in use. abort() is the limit.
When you call abort(), React stops waiting. Every boundary that has not finished keeps its fallback in the HTML and is marked for client rendering. The browser then renders those parts after the JavaScript loads. The user gets a page, though some content arrives later than it would have with a fast server.
The timer in the spine example has two gaps. It keeps running after a normal render, and it does not react to a client that disconnects. A more careful version clears the timer when the response finishes and aborts when the client goes away:
app.get('/safe', (req, res) => {
const { pipe, abort } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/static/client.js'],
onShellReady() {
res.setHeader('Content-Type', 'text/html');
pipe(res);
},
onShellError(error) {
console.error(error);
res.statusCode = 500;
res.setHeader('Content-Type', 'text/html');
res.send('<h1>Something went wrong</h1>');
},
onError(error) {
console.error(error);
}
});
const timer = setTimeout(() => abort(), 10000);
res.on('close', () => {
clearTimeout(timer);
abort();
});
});The close event fires when the response ends or the connection drops. Calling abort() after a finished render has no effect. Calling it after a client disconnect frees the work that is still pending.
Common errors
- Sending headers twice. Calling
res.sendinonShellErrorafterpipehas already started throws, because the headers are gone. The two callbacks are exclusive: the shell either becomes ready or fails. - Setting the status too late. Changing
res.statusCodeafterpipe(res)has no effect. Set it before. - Swallowing errors. An empty
onErrorhides failures that React recovered from. You then see only slow pages and client-side errors. - Waiting on
onAllReadyfor every request. This removes streaming. Use it only where you need complete HTML. - Treating abort as an error. After
abort(), React callsonErrorfor the boundaries it abandoned. Those entries in your log are expected when a timeout fires.
Exercises
Exercise
In the route above, a component inside a Suspense boundary throws while the shell is still rendering, and then the shell finishes successfully. What status code does the browser receive, and why?
Show answer
500. onError ran before onShellReady, so didError was true when the route set the status. The shell still streams normally and the boundary keeps its fallback.
Exercise
A data call inside a Suspense boundary takes 30 seconds, and your timeout is 10 seconds. What does the user see, and what do you see in the server log?
Show answer
The user receives the page with the boundary's fallback, and the client renders that boundary after hydration. The log shows an error passed to onError for the abandoned boundary, which comes from the abort and is expected.
Exercise
Why is pipe(res) never called when onShellError fires, and why does that let you send your own error page?
Show answer
The shell failed, so there is no valid HTML to stream. Because nothing has been written to the response, the status and headers are still unsent, and res.send can reply with a 500 page.