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
renderToPipeableStreaminstead.
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.
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
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 aHeadersinstance 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
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:
- If rendering the shell is successful, that Promise will resolve to a Readable Web Stream.
- If rendering the shell fails, the Promise will be rejected. Use this to output a fallback shell.
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 canawait stream.allReadybefore 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, "
async function handler(request) {
const stream = await renderToReadableStream(
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 (
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 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' };
async function handler(request) {
const stream = await renderToReadableStream(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
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:
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.
