renderToPipeableStream
renderToPipeableStream renders a React tree to a pipeable Node.js Stream.
const { pipe, abort } = renderToPipeableStream(reactNode, options?)
[!NOTE]
This API is specific to Node.js. Environments with Web Streams, like Deno and modern edge runtimes, should use
renderToReadableStreaminstead.
Reference
renderToPipeableStream(reactNode, options?)
Call renderToPipeableStream to render your React tree as HTML into a Node.js Stream.
import { renderToPipeableStream } from 'react-dom/server';
const { pipe } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/main.js'],
onShellReady() {
response.setHeader('content-type', 'text/html');
pipe(response);
}
});
On the client, call hydrateRoot to make the server-generated HTML interactive.
Parameters
-
reactNode: A React node you want to render to HTML. For example, a JSX element like<App />. It is expected to represent the entire document, so theAppcomponent should render the<html>tag. -
optional
options: An object with streaming options. - optional
bootstrapScriptContent: If specified, this string will be placed in an inline<script>tag. - optional
bootstrapScripts: An array of string URLs for the<script>tags to emit on the page. Use this to include the<script>that callshydrateRoot. Omit it if you don't want to run React on the client at all. - optional
bootstrapModules: LikebootstrapScripts, but emits<script type="module">instead. - optional
formState: The form state from a form submission handled by a Server Function. If the page is rendered in response to a submission of a form that usesuseActionStatewith apermalink, pass the resulting form state so that React embeds it into the HTML for hydration. The same value must be passed tohydrateRooton the client. This is typically passed through by your framework. - optional
identifierPrefix: A string prefix React uses for IDs generated byuseId. Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as passed tohydrateRoot. - optional
importMap: An import map object withimportsandscopesproperties. React emits it as an inline<script type="importmap">tag before any module scripts, so that<script type="module">tags (for example, frombootstrapModules) can use bare module specifiers. <CanaryBadge /> Whennonceis set, it is also applied to the import map script. - optional
maxHeadersLength: The maximum total length of the header content passed toonHeaders, measured in UTF-16 code units. Defaults to 2000. Once the limit is reached, React stops adding resource hints to the headers. - optional
namespaceURI: A string with the root namespace URI for the stream. Defaults to regular HTML. Pass'http://www.w3.org/2000/svg'for SVG or'http://www.w3.org/1998/Math/MathML'for MathML. - optional
nonce: Anoncestring to allow scripts forscript-srcContent-Security-Policy. To use different nonces for scripts and styles, pass an object withscriptandstyleproperties instead. - optional
onAllReady: A callback that fires when all rendering is complete, including both the shell and all additional content. You can use this instead ofonShellReadyfor crawlers and static generation. If you start streaming here, you won't get any progressive loading. The stream will contain the final HTML. - optional
onBrowserBailout: A callback React calls when it recovers frombrowser()by leaving a Suspense fallback for the browser to replace. It receives anErrordescribing the browser-only render and anerrorInfoobject containing thecomponentStack. If a reason was passed tobrowser, it is available aserror.cause. By default, React does nothing. See how to report browser-only rendering. - optional
onError: A callback that fires whenever there is a server error, whether recoverable or not. By default, this only callsconsole.error. If you override it to log crash reports, make sure that you still callconsole.error. You can also use it to adjust the status code before the shell is emitted. - optional
onHeaders: A callback that fires when React has determined the resource hints for the document, such as preconnects and stylesheet, font, or high-priority image preloads. It receives an object with aLinkproperty containing the correspondingLinkheader value, so you can send it as an HTTP response header or as a 103 Early Hints response. React calls it even when there are no resource hints to send. The header content is capped bymaxHeadersLength. - optional
onShellReady: A callback that fires right after the initial shell has been rendered. You can set the status code and callpipehere to start streaming. React will stream the additional content after the shell along with the inline<script>tags that replace the HTML loading fallbacks with the content. - optional
onShellError: A callback that fires if there was an error rendering the initial shell. It receives the error as an argument. No bytes were emitted from the stream yet, and neitheronShellReadynoronAllReadywill get called, so you can output a fallback HTML shell. - optional
progressiveChunkSize: The number of bytes in a chunk. Read more about the default heuristic.
Returns
renderToPipeableStream returns an object with two methods:
pipeoutputs the HTML into the provided Writable Node.js Stream. CallpipeinonShellReadyif you want to enable streaming, or inonAllReadyfor crawlers and static generation.abortlets you abort server rendering and render the rest on the client.
Usage
Rendering a React tree as HTML to a Node.js Stream
Call renderToPipeableStream to render your React tree as HTML into a Node.js Stream:
```js [[1, 5, "
// The route handler syntax depends on your backend framework
app.use('/', (request, response) => {
const { pipe } = renderToPipeableStream(
Along with the <CodeStep step={1}>root component</CodeStep>, you need to provide a list of <CodeStep step={2}>bootstrap `<script>` paths</CodeStep>. Your root component should return **the entire document including the root `<html>` tag.**
For example, it might look like this:
```js [[1, 1, "App"]]
export default function App() {
return (
<html>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="/styles.css"></link>
<title>My app</title>
</head>
<body>
<Router />
</body>
</html>
);
}
React will inject the doctype and your <CodeStep step={2}>bootstrap <script> tags</CodeStep> into the resulting HTML stream:
```html [[2, 5, "/main.js"]]
On the client, your bootstrap script should [hydrate the entire `document` with a call to `hydrateRoot`:](/reference/react-dom/client/hydrateRoot#hydrating-an-entire-document)
```js [[1, 4, "<App />"]]
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(document, <App />);
This will attach event listeners to the server-generated HTML and make it interactive.
[!INFO]
Reading CSS and JS asset paths from the build output
The final asset URLs (like JavaScript and CSS files) are often hashed after the build. For example, instead of
styles.cssyou might end up withstyles.123456.css. Hashing static asset filenames guarantees that every distinct build of the same asset will have a different filename. This is useful because it lets you safely enable long-term caching for static assets: a file with a certain name would never change content.However, if you don't know the asset URLs until after the build, there's no way for you to put them in the source code. For example, hardcoding
"/styles.css"into JSX like earlier wouldn't work. To keep them out of your source code, your root component can read the real filenames from a map passed as a prop:```js {1,6} export default function App({ assetMap }) { return ( ... ... ... ); }
>
> On the server, render `<App assetMap={assetMap} />` and pass your `assetMap` with the asset URLs:
>
```js {1-5,8,9}
// You'd need to get this JSON from your build tooling, e.g. read it from the build output.
const assetMap = {
'styles.css': '/styles.123456.css',
'main.js': '/main.123456.js'
};
app.use('/', (request, response) => {
const { pipe } = renderToPipeableStream(<App assetMap={assetMap} />, {
bootstrapScripts: [assetMap['main.js']],
onShellReady() {
response.setHeader('content-type', 'text/html');
pipe(response);
}
});
});
Since your server is now rendering
<App assetMap={assetMap} />, you need to render it withassetMapon the client too to avoid hydration errors. You can serialize and passassetMapto the client like this:```js {9-10} // You'd need to get this JSON from your build tooling. const assetMap = { 'styles.css': '/styles.123456.css', 'main.js': '/main.123456.js' };
app.use('/', (request, response) => {
const { pipe } = renderToPipeableStream(window.assetMap = ${JSON.stringify(assetMap)};,
bootstrapScripts: [assetMap['main.js']],
onShellReady() {
response.setHeader('content-type', 'text/html');
pipe(response);
}
});
});
>
> In the example above, the `bootstrapScriptContent` option adds an extra inline `<script>` tag that sets the global `window.assetMap` variable on the client. This lets the client code read the same `assetMap`:
>
```js {4}
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(document, <App assetMap={window.assetMap} />);
Both client and server render
Appwith the sameassetMapprop, so there are no hydration errors.
Streaming more content as it loads
Streaming allows the user to start seeing the content even before all the data has loaded on the server. For example, consider a profile page that shows a cover, a sidebar with friends and photos, and a list of posts:
function ProfilePage() {
return (
<ProfileLayout>
<ProfileCover />
<Sidebar>
<Friends />
<Photos />
</Sidebar>
<Posts />
</ProfileLayout>
);
}
Imagine that loading data for <Posts /> takes some time. Ideally, you'd want to show the rest of the profile page content to the user without waiting for the posts. To do this, wrap Posts in a <Suspense> boundary:
