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.

JavascriptReactData Fetching

Code

javascriptsnippet
40 lines
// 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);
  },
});

What the code does

React SSR Streaming With Suspense Boundaries keeps everything in the functions Comments and Page.

From react it pulls Suspense, renderToPipeableStream, Writable — the imports name exactly which library surface the snippet touches. Promise is not tied to any input check: it fires whenever execution reaches that line.

What to watch for

  • External dependency: react and react-dom/server — install them before running the snippet.

Applying it

Entry signature: function Comments({ postId })

Output lines are prefixed (chunk flushed:, ssr error:), making each step’s effect easy to spot.

Statements that matter

throw new Promise((resolve) => setTimeout(resolve, 200))
.then(() => null)
.finally(() => resolve());

FAQ

Is input validated before use?
There is no validation gate: the `Promise` raise happens unconditionally whenever its line executes.
Are there third-party dependencies?
`react` and `react-dom/server` — install them with the package manager before running.