Blogに戻る

Streaming SSR

#React #パフォーマンス #Web開発
作成日: 2024年2月18日
更新日: 2024年2月18日

Streaming SSRとは

Streaming SSRは、サーバーサイドレンダリングの結果を段階的にクライアントに送信する技術です。

従来のSSRとの違い

従来のSSR

// 全体のレンダリング完了後に送信
const html = ReactDOMServer.renderToString(<App />);
res.send(html);

Streaming SSR

// 段階的に送信
const stream = ReactDOMServer.renderToPipeableStream(<App />, {
  onShellReady() {
    res.statusCode = 200;
    res.setHeader('Content-type', 'text/html');
    stream.pipe(res);
  }
});

Suspenseとの組み合わせ

<Suspense fallback={<Loading />}>
  <SlowComponent />
</Suspense>

初期HTMLにはLoadingコンポーネントが含まれ、SlowComponentの準備ができ次第、ストリーミングで差し替えられます。

メリット