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 renderToReadableStream instead.


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.

See more examples below.

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 the App component 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 calls hydrateRoot. Omit it if you don't want to run React on the client at all.
  • optional bootstrapModules: Like bootstrapScripts, 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 uses useActionState with a permalink, pass the resulting form state so that React embeds it into the HTML for hydration. The same value must be passed to hydrateRoot on the client. This is typically passed through by your framework.
  • optional identifierPrefix: A string prefix React uses for IDs generated by useId. Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as passed to hydrateRoot.
  • optional importMap: An import map object with imports and scopes properties. React emits it as an inline <script type="importmap"> tag before any module scripts, so that <script type="module"> tags (for example, from bootstrapModules) can use bare module specifiers. <CanaryBadge /> When nonce is set, it is also applied to the import map script.
  • optional maxHeadersLength: The maximum total length of the header content passed to onHeaders, 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: A nonce string to allow scripts for script-src Content-Security-Policy. To use different nonces for scripts and styles, pass an object with script and style properties 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 of onShellReady for 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 from browser() by leaving a Suspense fallback for the browser to replace. It receives an Error describing the browser-only render and an errorInfo object containing the componentStack. If a reason was passed to browser, it is available as error.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 calls console.error. If you override it to log crash reports, make sure that you still call console.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 a Link property containing the corresponding Link header 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 by maxHeadersLength.
  • optional onShellReady: A callback that fires right after the initial shell has been rendered. You can set the status code and call pipe here 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 neither onShellReady nor onAllReady will 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:

  • pipe outputs the HTML into the provided Writable Node.js Stream. Call pipe in onShellReady if you want to enable streaming, or in onAllReady for crawlers and static generation.
  • abort lets 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, ""], [2, 6, "['/main.js']"]] import { renderToPipeableStream } from 'react-dom/server';

// The route handler syntax depends on your backend framework app.use('/', (request, response) => { const { pipe } = renderToPipeableStream(, { bootstrapScripts: ['/main.js'], onShellReady() { response.setHeader('content-type', 'text/html'); pipe(response); } }); });


Along with the &lt;CodeStep step={1}>root component&lt;/CodeStep>, you need to provide a list of &lt;CodeStep step={2}>bootstrap `<script>` paths&lt;/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.css you might end up with styles.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 with assetMap on the client too to avoid hydration errors. You can serialize and pass assetMap to 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(, { // Careful: It's safe to stringify() this because this data isn't user-generated. bootstrapScriptContent: 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 App with the same assetMap prop, 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: