Sub topic 12
Streaming HTML with renderToPipeableStream
This chapter assumes you can write function components and hooks, run a small Express server, and have a bundler that produces a client script. It also assumes you know what a Suspense boundary is. If not, read the previous chapter first.
Why stream
renderToString waits until the whole tree is rendered, then returns one string. One slow component delays the whole page. renderToPipeableStream returns a Node.js stream instead. It sends the HTML that is ready now, and sends the rest later as each part finishes.
The first piece it sends is the shell. The shell is everything outside any Suspense boundary that is still waiting for data. Parts inside a waiting boundary are replaced by their fallback. When the data arrives, React sends the real HTML and a small inline script that swaps it in place of the fallback.
The Suspense boundary
This page lets the article arrive at once and the comments arrive later.
import { lazy, Suspense } from 'react';
const Comments = lazy(() => import('./Comments.js'));
export default function Page() {
return (
<main>
<h1>Article</h1>
<Suspense fallback={<p>Loading comments...</p>}>
<Comments />
</Suspense>
</main>
);
}The server route
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);The options do the following:
bootstrapScriptsadds script tags that load your client bundle, which hydrates the page.onShellReadyruns when the shell is complete. You set the status and headers, then callpipe(res)to start sending.onShellErrorruns if the shell itself fails. Nothing has been sent yet, so you can still return a clean error page with a 500 status.onErrorruns for every error, including those inside a boundary after streaming has begun.abort()stops waiting. Boundaries that are unfinished are left as fallbacks, and the client tries to render them.
Status codes and errors
The status code and headers are sent with the first bytes, so you cannot change them later. If an error happens before onShellReady fires, didError lets you return 500. If it happens afterward, the status is already 200. Log it in onError.
Choosing the callback
onShellReady suits browsers, because users see content sooner. Crawlers and some bots prefer the full document. For them, React offers onAllReady, which fires when every boundary has finished.
Exercise
In the route above, a component inside a Suspense boundary throws an error after the shell has been sent. Which callback runs, and can the server change the response to a 500?
Show answer
onError runs, and onShellError does not. The server cannot change the status, because the 200 status and headers were already sent with the shell. React shows the fallback for that boundary and tries to render it on the client. Log the error in onError.