Sub topic 12
Streaming HTML with renderToPipeableStream
This chapter assumes you know how renderToString produces HTML and how hydrateRoot attaches React to it. It also assumes you can read a basic Express server. Here you will learn how renderToPipeableStream sends a page in pieces and what changes on the server when you use it.
Why renderToString falls short
renderToString is synchronous and all-or-nothing. It walks the whole tree and returns one string. The server cannot send a byte until every component has finished. If one component needs slow data, the whole page waits for it.
renderToPipeableStream removes that limit. It is the streaming renderer for Node.js. It writes HTML to a Node stream as parts of the tree become ready. Parts that are not ready are replaced by a Suspense fallback, and the real content arrives later in the same response.
| Concern | `renderToString` | `renderToPipeableStream` |
|---|---|---|
| Output | One string | A Node stream, written in chunks |
| Waits for slow data | Yes, for the whole tree | No, only inside Suspense boundaries |
| Suspense support | Fallback only, content rendered on the client | Fallback first, then content streamed in |
| Hydration | After the full page arrives | Can begin before all HTML has arrived |
| Runtime | Any JavaScript runtime | Node.js streams |
If you run on an edge runtime or Deno, use renderToReadableStream. It has the same model but returns a web ReadableStream. This chapter covers the Node version.
The shell and the stream
React splits the response into two parts.
- The shell is everything outside any Suspense boundary that has not resolved yet. It includes the layout, the headings, and the fallbacks for suspended boundaries.
- The later chunks carry the HTML for each suspended boundary once its content is ready.
Suppose a page renders an article and, below it, a comments component wrapped in <Suspense>. React renders the article and puts the fallback where the comments belong. That is the shell. When the comments finish loading, React sends their HTML as a new chunk. It also sends a small inline script that moves that HTML into place and removes the fallback. This works without any client JavaScript from your bundle, so the swap happens even before hydration.
The Suspense boundary
A boundary is what makes streaming useful. The page below lets the server send the article at once and stream the comments 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>
);
}Without the Suspense wrapper, a component that suspends would hold up the shell. With it, only that subtree waits. Place boundaries around content that is slow or less important, and leave the core page content outside them.
A complete Express route
This route streams the page, sends it once the shell is ready, handles shell failure, and gives up after 10 seconds.
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 call returns two functions and nothing is sent yet.
pipe(res)connects the render output to a writable stream. You call it yourself, and the timing is your choice. Call it too early and you lose the chance to set a correct status code.abort()stops rendering. React flushes what it has and leaves the unfinished boundaries to be rendered on the client.
The options used here do the following.
bootstrapScriptslists script URLs. React adds them to the HTML as<script>tags, and they load your client entry, which callshydrateRoot.onShellReadyfires when the shell is complete. This is the usual moment to start sending.onShellErrorfires if the shell itself cannot render. Nothing has been sent, so you can still reply with a plain error page and a 500 status.onErrorfires for every error, including those inside Suspense boundaries.
The next chapter goes deeper on these callbacks. For now, remember the order: set headers and status, then call pipe.
Why the status code matters
HTTP puts the status line and headers before the body. Once pipe(res) writes the first chunk, they are sent, and you cannot change the status afterward. Streaming therefore has a trade-off.
- If an error happens inside a Suspense boundary after the shell was sent, the response is already a 200. React falls back to rendering that boundary on the client.
- If you need the status to reflect any error on the page, you must wait for all content before sending. That removes the streaming benefit.
The example takes a middle path. It checks didError at onShellReady, so errors that happened before the shell was ready still produce a 500.
Choosing when to start sending
onShellReady is not the only option. The renderer also accepts onAllReady, which fires when the shell and all suspended content have finished.
| Callback | Starts sending | Good for |
|---|---|---|
| `onShellReady` | As soon as the shell is complete | Real users, where first paint speed matters |
| `onAllReady` | After the whole page has rendered | Search crawlers, static generation, tests |
A common pattern checks the user agent. Bots get onAllReady, so they receive the full page in one go with a correct status. People get onShellReady.
Gotchas in production
- Compression buffers the stream. Middleware such as
compressionmay hold chunks until its buffer fills, so the browser sees nothing early. Callres.flush()after writes, or configure the middleware to flush. - Proxies can buffer too. Some reverse proxies and CDNs collect the response before forwarding it. Check that yours passes chunks through.
- Don't write after
pipe. Once React owns the stream, writing your own HTML torescan corrupt the document. Put anything extra in the React tree. - Server work still blocks. Rendering is CPU work on the Node event loop. Streaming improves how soon the browser gets bytes. It does not reduce the total render cost per request.
- Always set a timeout. A boundary that never resolves would keep the response open. The
abort()call after 10 seconds bounds that.
Streaming and hydration together
Streaming is half of the story. The browser also has to hydrate the streamed HTML. Because each Suspense boundary is a separate unit, the client can hydrate the shell first and hydrate each boundary as its code and HTML arrive. That behavior is called selective hydration, and a later chapter covers it.
Exercise
A route uses renderToPipeableStream and calls pipe(res) inside onShellReady. A database query inside a Suspense boundary fails 2 seconds later. What status code does the browser receive, and why? What would you change if search crawlers must see a 500 for this case?
Show answer
The browser receives 200. The status line and headers were sent with the shell, before the query failed, so they cannot change. React renders that boundary on the client instead. To get a 500 for crawlers, detect them by user agent and start sending from onAllReady rather than onShellReady, setting the status from the didError flag set in onError before calling pipe.
Exercise
Why does the example call setTimeout(() => abort(), 10000), and what does abort do to unfinished Suspense boundaries?
Show answer
The timeout stops a boundary that never resolves from keeping the response open forever. abort() makes React flush what it has already rendered and finish the response. Unfinished boundaries are left to be rendered on the client.