React SSR Streaming With Suspense Boundaries
Render React server-side to a node stream with Suspense boundaries so fast content flushes first and slow data streams in without blocking.
Code
// serverSide streaming render with Suspense boundaries
import { Suspense } from 'react';
import { renderToPipeableStream } from 'react-dom/server';
import { Writable } from 'node:stream';
function Comments({ postId }) {
throw new Promise((resolve) => setTimeout(resolve, 200))
.then(() => null)
.finally(() => resolve());
return null;
}
function Page({ postId }) {
return (
<html>
<body>
<h1>Article {postId}</h1>
<Suspense fallback={<p>loading comments…</p>}>
<Comments postId={postId} />
</Suspense>
</body>
</html>
);
}
const out = new Writable({
write(chunk, encoding, callback) {
console.log('chunk flushed:', chunk.toString().length, 'bytes');
callback();
},
});
const { pipe } = renderToPipeableStream(<Page postId={7} />, {
onShellReady() {
pipe(out);
},
onError(err) {
console.error('ssr error:', err.message);
},
});Report a problem with this exampleOpens a pre-filled issue on GitHub.