К основному содержанию
скилл CX Codex

streaming-ssr — скилл для Claude Code: стриминг SSR в React

Учит агента отдавать HTML чанками через renderToPipeableStream и Suspense. Пригодится, когда страница большая и ждать полной отрисовки перед первым байтом нельзя.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add PatternsDev/skills --skill streaming-ssr -a claude-code
Открыть на GitHub

Что делает streaming-ssr

Скилл объясняет, как перейти от renderToString к потоковой отдаче. Вместо одной длинной строки HTML сервер сначала отправляет оболочку, а медленные части досылает по мере готовности. Клиент начинает парсить и рисовать страницу с первых байтов, поэтому TTFB перестаёт расти вместе с размером страницы.

Внутри — инструкции по API React 18: renderToPipeableStream для Node, renderToReadableStream для Web Streams, колбэки onShellReady и onError, связка с Suspense и hydrateRoot() на клиенте. Есть пример HTML-оболочки и рабочий обработчик Express, который отдаёт поток в response.

Простой заменой renderToString на renderToPipeableStream дело не ограничивается. Код, который собирает разметку через renderToStaticMarkup и вставляет в неё результат renderToString, на поток не переводится — там ждут именно строку. Ещё стриминг теряет смысл, если хостинг или обратный прокси буферизуют ответ целиком: сервер отдаёт чанки, а до браузера они доходят одним куском. Это повод проверить свой стек до того, как переписывать рендер.

Какие задачи решает

  • снизить Time to First Byte на больших страницах
  • начать отрисовку до готовности всего дерева компонентов
  • подружить медленные блоки со Suspense
  • перевести Express-обработчик на потоковую отдачу HTML
  • пережить сетевую перегрузку без роста памяти на сервере

Примеры запросов агенту

  • Переведи рендер этой страницы на streaming SSR через renderToPipeableStream
  • Оберни медленный блок в Suspense, чтобы он досылался после оболочки
  • Проверь, не буферизует ли ответ наш прокси, иначе стриминг не даст выигрыша

Как установить streaming-ssr

1Через Skills CLI (Vercel)

npx skills add PatternsDev/skills --skill streaming-ssr -a claude-code

2Вручную: положить файлы

~/.claude/skills/streaming-ssr/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/streaming-ssr/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о streaming-ssr

Как установить streaming-ssr в Claude?

Выполните npx skills add PatternsDev/skills --skill streaming-ssr -a claude-code. Скилл появится в ~/.claude/skills/streaming-ssr/SKILL.md.

Что делает streaming-ssr?

Учит агента отдавать HTML чанками: сначала оболочку, потом медленные части. Это снижает TTFB и ускоряет первую отрисовку на больших страницах.

Когда стриминг SSR не сработает?

Если хостинг или обратный прокси буферизуют ответ целиком, выигрыша не будет. Также не переводится код, где renderToStaticMarkup собирает шаблон, а renderToString вставляет в него разметку компонента.

Исходный текст

SKILL.md · MIT
---
name: streaming-ssr
description: Teaches streaming server-side rendering for chunked HTML delivery. Use when you need faster Time to First Byte and First Contentful Paint by streaming HTML as it's generated on the server.
paths:
  - "**/*.tsx"
  - "**/*.jsx"
license: MIT
metadata:
  author: patterns.dev
  version: "1.1"
related_skills:
  - "hooks-pattern"
  - "hoc-pattern"
---

# Streaming Server-Side Rendering

We can reduce the Time To Interactive while still server rendering our application by _streaming_ the contents of our application. Instead of generating one large HTML string containing the necessary markup for the current navigation, we can send the shell first and stream slower parts later. The moment the client receives the first chunks of HTML, it can start parsing and painting the page.

Modern React streaming uses `renderToPipeableStream()` on Node runtimes or `renderToReadableStream()` on Web Stream runtimes, then hydrates the response with `hydrateRoot()` on the client.

## When to Use

- Use this when you want to improve TTFB and FCP by sending HTML incrementally as it's generated
- This is helpful for large pages where waiting for the full HTML would delay the initial paint

## When NOT to Use

- When your hosting environment doesn't support streaming responses (some serverless platforms buffer the full response)
- For simple static pages where the HTML is small enough that streaming provides no meaningful improvement
- When middleware or reverse proxies in your stack buffer the response, negating the streaming benefit

## Instructions

- Use `renderToPipeableStream` (React 18+) instead of the deprecated `renderToNodeStream`
- Combine streaming with `Suspense` boundaries to stream partial content while slow parts load
- Use the `onShellReady` callback to begin streaming once the critical shell is ready
- Handle streaming errors with the `onError` callback

## Details

The initial HTML gets sent to the response object alongside the chunks of data from the App component:

```html
<!DOCTYPE html>
<html>
  <head>
    <title>Cat Facts</title>
    <link rel="stylesheet" href="/style.css" />
    <script type="module" defer src="/build/client.js"></script>
  </head>
  <body>
    <h1>Stream Rendered Cat Facts!</h1>
    <div id="approot"></div>
  </body>
</html>
```

Modern React streaming on Node uses `renderToPipeableStream`:

```js
import { renderToPipeableStream } from "react-dom/server";

app.use("*", (request, response) => {
  let didError = false;

  const { pipe } = renderToPipeableStream(<App />, {
    bootstrapScripts: ["/build/client.js"],
    onShellReady() {
      response.statusCode = didError ? 500 : 200;
      response.setHeader("Content-Type", "text/html");
      pipe(response);
    },
    onError(error) {
      didError = true;
      console.error(error);
    },
  });
});
```

If we were to server render the `App` component using `renderToString`, we would have to wait until the entire tree had rendered before sending the response. With streaming, the server can flush the shell early and continue sending slower content as it becomes ready.

### Concepts

Like progressive hydration, streaming is another rendering mechanism that can be used to improve SSR performance. As the name suggests, streaming implies chunks of HTML are streamed from the node server to the client as they are generated. As the client starts receiving "bytes" of HTML earlier even for large pages, the TTFB is reduced and relatively constant. All major browsers start parsing and rendering streamed content or the partial response earlier. As the rendering is progressive, it results in a fast FP and FCP.

Streaming responds well to network backpressure. If the network is clogged and not able to transfer any more bytes, the renderer gets a signal and stops streaming till the network is cleared up. Thus, the server uses less memory and is more responsive to I/O conditions. This enables your Node.js server to render multiple requests at the same time and prevents heavier requests from blocking lighter requests for a long time. As a result, the site stays responsive even in challenging conditions.

### React for Streaming

React 18 introduced the modern streaming APIs:

1. **`renderToPipeableStream(element, options)`** for Node.js HTTP responses.
2. **`renderToReadableStream(element, options)`** for Web Streams runtimes such as edge environments.

These APIs support Suspense boundaries, `onShellReady`, `onAllReady`, and progressive hydration through `hydrateRoot()` on the client.

The stream output can emit bytes as soon as the shell is ready. The response progressively sends chunks of data to the client while slower chunks continue rendering on the server.

### Streaming SSR - Pros and Cons

Streaming aims to improve the speed of SSR with React and provides the following benefits:

1. **Performance Improvement:** As the first byte reaches the client soon after rendering starts on the server, the TTFB is better than that for SSR. It is also more consistent irrespective of the page size. Since the client can start parsing HTML as soon as it receives it, the FP and FCP are also lower.

2. **Handling of Backpressure**: Streaming responds well to network backpressure or congestion and can result in responsive websites even under challenging conditions.

3. **Supports SEO**: The streamed response can be read by search engine crawlers, thus allowing for SEO on the website.

It is important to note that streaming implementation is not a simple find-replace from `renderToString` to `renderToPipeableStream()`. There are cases where the code that works with SSR may not work as-is with streaming:

1. Frameworks that use the server-render-pass to generate markup that needs to be added to the document before the SSR-ed chunk. Examples are frameworks that dynamically determine which CSS to add to the page in a preceding `<style>` tag.

2. Code, where `renderToStaticMarkup` is used to generate the page template and `renderToString` calls are embedded to generate dynamic content. Since the string corresponding to the component is expected in these cases, it cannot be replaced by a stream. For example:

```js
res.write("<!DOCTYPE html>");

res.write(renderToStaticMarkup(
 <html>
   <head>
     <title>My Page</title>
   </head>
   <body>
     <div id="content">
       { renderToString(<MyPage/>) }
     </div>
   </body>
 </html>);
```

Both Streaming and Progressive Hydration can help to bridge the gap between a pure SSR and a CSR experience.

## Source

- [patterns.dev/react/streaming-ssr](https://patterns.dev/react/streaming-ssr)

© patterns.dev · MIT · PatternsDev/skills

Похожие скиллы

Всё по теме «Фронтенд и UI» →
bun-react-ssr secondsky Скилл для сборки серверного React на Bun: renderToString, стриминг, гидратация и свой роутер без фреймворка. CX Codex +1 395установок aws-messaging-and-streaming aws Помогает агенту выбрать, чем двигать данные в AWS: очередью, шиной событий или журналом. Полезно до того, как вы зафиксируете SQS или Kinesis. CX Codex +1 8 100установок streaming assistant-ui Скилл по проводным протоколам и бэкенд-хелперам assistant-ui: помогает собрать свой стриминговый эндпоинт и разобрать формат чанков. CX Codex +1 6 400установок angular-ssr analogjs Скилл для задач Angular SSR, гидратации и пререндеринга. Он устарел: текущая версия больше не поддерживается. CX Codex +1 3 900установок google-cloud-solution-agentic-ai-bidirectional-streaming официальный google Скилл помогает спроектировать решение Google Cloud для двусторонней потоковой обработки аудио, видео и текста с ИИ-агентами. Подходит для технических подсказок и контроля безопасности. CX Codex 5 411установок inngest-realtime inngest Скилл учит агента публиковать обновления из durable-функций Inngest в живой интерфейс: статусы заказов, стриминг токенов, логи и подтверждения от пользователя. CX Codex +1 797установок

Из того же набора44

react-selective-hydration Скилл учит агента настраивать выборочную гидратацию и потоковый SSR в React 18+. Пригодится, когда тяжёлые компоненты с запросами данных тормозят интерактивность страницы. CX Codex +1 943установок server-side-rendering Скилл объясняет серверный рендеринг в React и подсказывает, когда он оправдан, а когда хватит статики или клиентского рендеринга. CX Codex +1 942установок incremental-static-rendering Скилл учит агента настраивать Incremental Static Regeneration в Next.js. Он помогает обновлять статичные страницы без полной пересборки сайта. CX Codex +1 918установок static-rendering Скилл объясняет статическую генерацию: какие страницы можно собрать в HTML заранее и как это сделать в Next.js. Пригодится, когда контент не меняется от запроса к запросу. CX Codex +1 910установок js-performance-patterns Набор паттернов микрооптимизации JavaScript для горячих путей. Помогает агенту устранять просадки скорости в циклах, обработчиках событий и операциях с DOM. CX Codex +1 687установок view-transitions Учит агента работать с View Transitions API: переходы между страницами и состояниями интерфейса браузер анимирует сам. CX Codex +1 678установок vite-bundle-optimization Скилл с паттернами оптимизации бандла и сборки в Vite + React. Пригодится, когда билд тормозит или чанки выходят больше ожидаемого. CX Codex +1 667установок command-pattern Обучает агента паттерну «Команда» для JavaScript и TypeScript. Помогает разделить вызов операции и её выполнение, настроить очередь задач или историю отмены. CX Codex +1 645установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой