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

server-side-rendering — скилл для Claude Code: SSR в React

Скилл объясняет серверный рендеринг в React и подсказывает, когда он оправдан, а когда хватит статики или клиентского рендеринга.

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

Что делает server-side-rendering

Скилл включается на файлах **/*.tsx и **/*.jsx и разбирает с агентом, как устроен SSR: сервер отдаёт готовый HTML в ответ на запрос, данные из базы или внешнего API подтягиваются там же, а клиентский JavaScript для отрисовки не нужен. Из-за этого первый контент появляется раньше, а краулеры видят содержимое страницы.

Внутри — разделы «когда использовать» и «когда не использовать», инструкции и примеры. Агент предложит фреймворк с встроенной поддержкой вроде Next.js, renderToPipeableStream из React 18+ для стриминга с Suspense, гидratацию для интерактивных страниц. Есть разбор getServerSideProps() с фетчем данных и передачей их в компонент через props.

Главное ограничение — TTFB. Каждый запрос сервер обрабатывает заново, поэтому при наплыве пользователей, медленной сети или неоптимизированном серверном коде ответ задерживается. Часть взаимодействий требует полной перезагрузки страницы, одностраничное приложение на чистом SSR не собрать. Для внутренних дашбордов, где SEO неважно, скилл сам советует не брать SSR. Установка идёт через npx skills add, лицензия MIT.

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

  • отдать поисковикам готовый HTML вместо пустой оболочки
  • сократить время до первого контента на тяжёлых страницах
  • подтянуть данные из API на сервере и передать их в компонент
  • выбрать между SSR, статикой и клиентским рендерингом для конкретной страницы
  • перевести страницу на стриминг с Suspense

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

  • Помоги настроить SSR для страницы со списком пользователей на Next.js
  • Стоит ли делать серверный рендеринг для этой страницы или хватит статики?
  • Перепиши этот компонент под getServerSideProps() с фетчем данных

Как установить server-side-rendering

1Через Skills CLI (Vercel)

npx skills add PatternsDev/skills --skill server-side-rendering -a claude-code

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

~/.claude/skills/server-side-rendering/SKILL.md

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

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

Вопросы о server-side-rendering

Как установить server-side-rendering в Claude?

Выполните npx skills add PatternsDev/skills --skill server-side-rendering -a claude-code. Файл скилла окажется по пути ~/.claude/skills/server-side-rendering/SKILL.md.

Что делает этот скилл?

Учит агента серверному рендерингу в React: когда он уместен, как связать SSR с гидratацией и какие фреймворки дают поддержку из коробки.

Когда SSR лучше не применять?

Для чисто статичного контента, где хватает SSG, и для внутренних дашбордов, где SEO не играет роли. Ещё один повод отказаться — высокая стоимость рендеринга на каждый запрос без возможности кешировать.

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

SKILL.md · MIT
---
name: server-side-rendering
description: Teaches server-side rendering (SSR) for React applications. Use when you need faster initial page loads, better SEO, or dynamic per-request HTML generation.
paths:
  - "**/*.tsx"
  - "**/*.jsx"
license: MIT
metadata:
  author: patterns.dev
  version: "1.1"
related_skills:
  - "hooks-pattern"
  - "hoc-pattern"
---

# Server-side Rendering

## Table of Contents

- [When to Use](#when-to-use)
- [When NOT to Use](#when-not-to-use)
- [Instructions](#instructions)
- [Details](#details)
- [Source](#source)

Server-side rendering (SSR) is one of the oldest methods of rendering web content. SSR generates the full HTML for the page content to be rendered in response to a user request. The content may include data from a datastore or external API.

The connect and fetch operations are handled on the server. HTML required to format the content is also generated on the server. Thus, with SSR we can avoid making additional round trips for data fetching and templating. As such, rendering code is not required on the client and the JavaScript corresponding to this need not be sent to the client.

## When to Use

- Use this when SEO and fast First Contentful Paint are important for your application
- This is helpful for content-heavy pages that need to be quickly visible to users and search engines

## When NOT to Use

- For purely static content where static rendering (SSG) is sufficient and avoids per-request server cost
- For internal dashboards or tools where SEO is irrelevant and CSR provides a simpler architecture
- When the server rendering overhead per request is too high and caching isn't feasible

## Instructions

- Use frameworks like Next.js that provide built-in SSR support
- Consider upgrading to `renderToPipeableStream` (React 18+) for streaming SSR with Suspense support
- Combine SSR with client-side hydration for interactive pages
- Be aware of TTFB implications — optimize server response times and consider caching
- Explore React Server Components as a complement to SSR for reducing client-side JavaScript

## Details

With SSR every request is treated independently and will be processed as a new request by the server. Even if the output of two consecutive requests is not very different, the server will process and generate it from scratch. Since the server is common to multiple users, the processing capability is shared by all active users at a given time.

### Classic SSR Implementation

Consider a simple example showing and updating the current time on a page using classic SSR and JavaScript.

```html
<!DOCTYPE html>
<html>
   <head>
       <title>Time</title>
   </head>
   <body>
       <div>
       <h1>Hello, world!</h1>
       <b>It is <div id=currentTime></div></b>
       </div>
   </body>
</html>
```

```js
function tick() {
    var d = new Date();
    var n = d.toLocaleTimeString();
    document.getElementById("currentTime").innerHTML = n;
}
setInterval(tick, 1000);
```

Note how this is different from the CSR code that provides the same output. Also note that, while the HTML is rendered by the server, the time displayed here is the local time on the client as populated by the JavaScript function `tick()`. If you want to display any other data that is server specific, e.g., server time, you will need to embed it in the HTML before it is rendered. This means it will not get refreshed automatically without a round trip to the server.

### Pros and Cons

Executing the rendering code on the server and reducing JavaScript offers the following advantages.

#### Lesser JavaScript leads to quicker FCP and TTI

In cases where there are multiple UI elements and application logic on the page, SSR has considerably less JavaScript when compared to CSR. The time required to load and process the script is thus lesser. FP, FCP and TTI are shorter and FCP = TTI. With SSR, users will not be left waiting for all the screen elements to appear and for it to become interactive.

#### Provides additional budget for client-side JavaScript

Development teams are required to work with a JS budget that limits the amount of JS on the page to achieve the desired performance. With SSR, since you are directly eliminating the JS required to render the page, it creates additional space for any third party JS that may be required by the application.

#### SEO enabled

Search engine crawlers are easily able to crawl the content of an SSR application thus ensuring higher search engine optimization on the page.

SSR works great for static content due to the above advantages. However, it does have a few disadvantages because of which it is not perfect for all scenarios.

#### Slow TTFB

Since all processing takes place on the server, the response from the server may be delayed in case of one or more of the following scenarios:

- Multiple simultaneous users causing excess load on the server.
- Slow network
- Server code not optimized.

#### Full page reloads required for some interactions

Since all code is not available on the client, frequent round trips to the server are required for all key operations causing full page reloads. This could increase the time between interactions as users are required to wait longer between operations. A single-page application is thus not possible with SSR.

### SSR with Next.js

The Next.js framework also supports SSR. This pre-renders a page on the server on every request. It can be accomplished by exporting an async function called [`getServerSideProps()`](https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering) from a page as follows.

```js
export async function getServerSideProps(context) {
  return {
    props: {}, // will be passed to the page component as props
  };
}
```

The context object contains keys for HTTP request and response objects, routing parameters, querystring, locale, etc.

The following implementation shows the use of `getServerSideProps()` for rendering data on a page formatted using React:

```js
// data fetched from an external data source using `getServerSideProps`

const Users = ({ users, error }) => {
 return (
   <section>
     <header>
       <h1>List of users</h1>
     </header>
     {error && <div>There was an error.</div>}
     {!error && users && (
       <table>
         <thead>
           <tr>
             <th>Username</th>
             <th>Email</th>
             <th>Name</th>
           </tr>
         </thead>
         <tbody>
           {users.map((user, key) => (
             <tr key={key}>
               <td>{user.username}</td>
               <td>{user.email}</td>
               <td>{user.name}</td>
             </tr>
           ))}
         </tbody>
       </table>
     )}
   </section>
 );
};

export async function getServerSideProps() {
 try {
   // Fetch data from external API
   const res = await fetch("https://jsonplaceholder.typicode.com/users");
   const data = await res.json();

   // Pass data to the page via props
   return { props: { users: data, error: null } };
 } catch (error) {
   return { props: { users: null, error: true } };
 }
}

export default Users;
```

### React for the Server

React can be rendered isomorphically, which means that it can function both on the browser as well as other platforms like the server. Thus, UI elements may be rendered on the server using React.

React can also be used with universal code which will allow the same code to run in multiple environments. This is made possible by using Node.js on the server.

```js
ReactDOMServer.renderToString(element);
```

This function returns an HTML string corresponding to the React element. The HTML can then be rendered to the client for a faster page load.

The `renderToString()` function may be used with `hydrateRoot()`. This preserves the HTML rendered on the server and attaches event handlers on the client.

To implement this, we use a `.js` file on both client and server corresponding to every page. The `.js` file on the server will render the HTML content, and the `.js` file on the client will hydrate it.

The server code:

```js
app.get("/", (req, res) => {
  const app = ReactDOMServer.renderToString(<App />);
});
```

The client-side code to ensure the element `App` is hydrated:

```js
import { hydrateRoot } from "react-dom/client";

hydrateRoot(document.getElementById("root"), <App />);
```

A complete example of SSR with React can be found [here](https://www.digitalocean.com/community/tutorials/react-server-side-rendering).

## Source

- [patterns.dev/react/server-side-rendering](https://patterns.dev/react/server-side-rendering)

© patterns.dev · MIT · PatternsDev/skills

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

Всё по теме «Фронтенд и UI» →
nextjs-typescript-tailwindcss-supabase Mindrally Скилл задаёт агенту правила для Next.js 14, TypeScript, TailwindCSS и Supabase: серверные компоненты, обработка ошибок, читаемый код. CX Codex +1 1 300установок next vercel-labs Генерирует многостраничные приложения Next.js из спецификаций JSON. Пригодится при сборке SSR-сайтов, маршрутов и макетов через @json-render/next. CX Codex +1 8 600установок framer-motion-react C-Jeril Скилл по Framer Motion для React и Next.js: AnimatePresence, layout-анимации, useAnimation и обход проблем с SSR. CX Codex +1 822установок material-ui-nextjs mui Скилл для связки Material UI с Next.js: SSR, кеш Emotion, next/font, CSS-слои, Link и useSearchParams. Пригодится при настройке или отладке MUI в Next.js-приложении. CX Codex +1 727установок react-patterns affaan-m Скилл для Claude и других ИИ-редакторов: подсказывает, как писать компоненты React 18/19 — хуки, границы серверных и клиентских компонентов, формы, загрузку данных. CX Codex +1 4 900установок feature-sliced-design feature-sliced Скилл помогает раскладывать frontend-код по слоям Feature-Sliced Design и проверять границы импортов. Пригодится при создании и миграции проектов. CX Codex +1 23 600установок

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

compound-pattern Учит агента собирать составные компоненты с общим неявным состоянием: табы, аккордеоны, выпадающие меню. Пригодится, когда подкомпоненты должны согласовывать поведение без прокидывания пропсов. CX Codex +1 1 000установок react-server-components Скилл объясняет React Server Components: какие компоненты рендерить на сервере и где ставить 'use client'. Пригодится в Next.js App Router. CX Codex +1 954установок progressive-hydration Скилл объясняет агенту, как разбить гидратацию серверного React-приложения на части и отложить JavaScript для неважных блоков. CX Codex +1 952установок react-selective-hydration Скилл учит агента настраивать выборочную гидратацию и потоковый SSR в React 18+. Пригодится, когда тяжёлые компоненты с запросами данных тормозят интерактивность страницы. CX Codex +1 943установок incremental-static-rendering Скилл учит агента настраивать Incremental Static Regeneration в Next.js. Он помогает обновлять статичные страницы без полной пересборки сайта. CX Codex +1 918установок static-rendering Скилл объясняет статическую генерацию: какие страницы можно собрать в HTML заранее и как это сделать в Next.js. Пригодится, когда контент не меняется от запроса к запросу. CX Codex +1 910установок streaming-ssr Учит агента отдавать HTML чанками через renderToPipeableStream и Suspense. Пригодится, когда страница большая и ждать полной отрисовки перед первым байтом нельзя. CX Codex +1 883установок js-performance-patterns Набор паттернов микрооптимизации JavaScript для горячих путей. Помогает агенту устранять просадки скорости в циклах, обработчиках событий и операциях с DOM. CX Codex +1 687установок

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

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