React & Modern Frontend (445 Qs)•Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)
What is the purpose of renderToNodeStream method?
The ReactDOMServer#renderToNodeStream method is used to generate HTML on the server and send the markup down on the initial request for faster page loads. It also helps search engines to crawl your pages easily for SEO purposes.
Note: Remember this method is not available in the browser but only server.
Code Example
tsx
import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { App } from './App';
const server = express();
server.get('*', (req, res) => {
res.write('<!DOCTYPE html><html><head><title>SSR App</title></head><body><div id="root">');
// renderToNodeStream streams HTML chunks as they are generated
const stream = ReactDOMServer.renderToNodeStream(<App />);
stream.pipe(res, { end: false });
stream.on('end', () => {
res.write('</div><script src="/bundle.js"></script></body></html>');
res.end();
});
});