renderToNodeStream
renderToNodeStream
renders a React tree to a Node.js Readable Stream.
const stream = renderToNodeStream(reactNode)
Reference
renderToNodeStream(reactNode)
On the server, call renderToNodeStream
to get a Node.js Readable Stream which you can pipe into the response.
import { renderToNodeStream } from 'react-dom/server';
const stream = renderToNodeStream(<App />);
stream.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 />
. -
optional
options
: An object for server render.- 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
Returns
A Node.js Readable Stream that outputs an HTML string.
Caveats
-
This method will wait for all Suspense boundaries to complete before returning any output.
-
As of React 18, this method buffers all of its output, so it doesn’t actually provide any streaming benefits. This is why it’s recommended that you migrate to
renderToPipeableStream
instead. -
The returned stream is a byte stream encoded in utf-8. If you need a stream in another encoding, take a look at a project like iconv-lite, which provides transform streams for transcoding text.
Usage
Rendering a React tree as HTML to a Node.js Readable Stream
Call renderToNodeStream
to get a Node.js Readable Stream which you can pipe to your server response:
import { renderToNodeStream } from 'react-dom/server';
// The route handler syntax depends on your backend framework
app.use('/', (request, response) => {
const stream = renderToNodeStream(<App />);
stream.pipe(response);
});
The stream will produce the initial non-interactive HTML output of your React components. On the client, you will need to call hydrateRoot
to hydrate that server-generated HTML and make it interactive.