renderStreaming

Used for React v18+ Streaming SSR to render readable streams, used in conjunction with createRequestHandler.

Usage

src/entry.server.tsx
import {
  renderStreaming,
  createRequestHandler,
} from '@modern-js/runtime/ssr/server';

const handleRequest = async (request, ServerRoot, options) => {
  const stream = await renderStreaming(request, <ServerRoot />, options);

  return new Response(stream, {
    headers: {
      'content-type': 'text/html; charset=utf-8',
    },
  });
};

export default createRequestHandler(handleRequest);

Function Signature

export type RenderStreaming = (
  request: Request,
  serverRoot: React.ReactElement,
  optinos: RenderOptions,
) => Promise<ReadableStream>;

Example

src/entry.server.tsx
import {
  renderStreaming,
  createRequestHandler,
} from '@modern-js/runtime/ssr/server';

const handleRequest = async (request, ServerRoot, options) => {
  // do something before render
  const stream = await renderStreaming(request, <ServerRoot />, options);

  // docs: https://developer.mozilla.org/en-US/docs/Web/API/TransformStream
  const transformStream = new TransformStream({
    transform(chunk, controller) {
      // do some transform
    },
  });

  stream.pipeThrough(transformStream);

  return new Response(transformStream.readable, {
    headers: {
      'content-type': 'text/html; charset=utf-8',
    },
  });
};

export default createRequestHandler(handleRequest);