renderToReadableStream

renderToReadableStream renders a React tree to a Readable Web Stream.

const stream = await renderToReadableStream(reactNode, options?)

[!NOTE]

This API depends on Web Streams. For Node.js, use renderToPipeableStream instead.


Reference

renderToReadableStream(reactNode, options?)

Call renderToReadableStream to render your React tree as HTML into a Readable Web Stream.

import { renderToReadableStream } from 'react-dom/server';

async function handler(request) {
  const stream = await renderToReadableStream(<App />, {
    bootstrapScripts: ['/main.js']
  });
  return new Response(stream, {
    headers: { 'content-type': 'text/html' },
  });
}

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 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 a Headers instance 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 progressiveChunkSize: The number of bytes in a chunk. Read more about the default heuristic.
  • optional signal: An abort signal that lets you abort server rendering and render the rest on the client.

Returns

renderToReadableStream returns a Promise:

The returned stream has an additional property:

  • allReady: A Promise that resolves when all rendering is complete, including both the shell and all additional content. You can await stream.allReady before returning a response for crawlers and static generation. If you do that, you won't get any progressive loading. The stream will contain the final HTML.

Usage

Rendering a React tree as HTML to a Readable Web Stream

Call renderToReadableStream to render your React tree as HTML into a Readable Web Stream:

```js [[1, 4, ""], [2, 5, "['/main.js']"]] import { renderToReadableStream } from 'react-dom/server';

async function handler(request) { const stream = await renderToReadableStream(, { bootstrapScripts: ['/main.js'] }); return new Response(stream, { headers: { 'content-type': 'text/html' }, }); }


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 ( My app ... ); }

>
> 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'
};

async function handler(request) {
  const stream = await renderToReadableStream(<App assetMap={assetMap} />, {
    bootstrapScripts: [assetMap['/main.js']]
  });
  return new Response(stream, {
    headers: { 'content-type': 'text/html' },
  });
}

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' };

async function handler(request) { const stream = await renderToReadableStream(, { // Careful: It's safe to stringify() this because this data isn't user-generated. bootstrapScriptContent: window.assetMap = ${JSON.stringify(assetMap)};, bootstrapScripts: [assetMap['/main.js']], }); return new Response(stream, { headers: { 'content-type': 'text/html' }, }); }

>
> 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:

js {9,11} function ProfilePage() { return ( <ProfileLayout> <ProfileCover /> <Sidebar> <Friends /> <Photos /> </Sidebar> <Suspense fallback={<PostsGlimmer />}> <Posts /> </Suspense> </ProfileLayout> ); }

This tells React to start streaming the HTML before Posts loads its data. React will send the HTML for the loading fallback (PostsGlimmer) first, and then, when Posts finishes loading its data, React will send the remaining HTML along with an inline <script> tag that replaces the loading fallback with that HTML. From the user's perspective, the page will first appear with the PostsGlimmer, later replaced by the Posts.