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

cache-components · laguagu — скилл для Claude Code: кэширование в Next.js

Скилл cache-components даёт экспертные советы по кэшированию компонентов и частичному предрендерингу в Next.js 16.4+.

MIT 222 установок ★ 74 обновлён 2026-11-14

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

Что делает cache-components

Скилл разбирается в Next.js Cache Components и Partial Prerendering (PPR) — технологиях, которые заменили старые флаги experimental.dynamicIO, experimental.useCache и experimental.ppr. Работает с Next.js 16.4.1 и выше: в версиях 16.0.0–16.4.0 директива use cache имеет уязвимость (GHSA-673q-mjm6-r5xr), позволяющую неавторизованное удалённое выполнение кода при возврате типизированных массивов — обновление обязательно.

Скилл помогает разобраться с граница между кэшируемым контентом и динамическим, правильно использовать cacheLife() для установки времени жизни, cacheTag() для тегирования, updateTag() и revalidateTag() для инвалидации. Объясняет, когда нужна директива use cache: private (запускается на время запроса, не входит в статическую оболочку), как устроены GET Route Handler, pass-through и interleaving паттерны. Может провести отладку проблем с кэшем и проверить реализацию.

Внутри скилл обращается к документации, которая поставляется вместе с Next.js в папке node_modules/next/dist/docs/ (с версии 16.2), и к типам в node_modules/next/cache.d.ts. Перед работой советует проверить версию Next.js и наличие флагов cacheComponents и partialPrefetching в конфиге — они должны быть явно включены.

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

  • настроить кэширование компонентов в Next.js 16.4+
  • установить время жизни кэша через cacheLife() и профили
  • тегировать данные cacheTag() и инвалидировать через updateTag()
  • отделить статический контент от динамического с правильными границами
  • отладить проблемы с кэшем и Partial Prerendering

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

  • Помоги реализовать use cache функцию для получения списка постов с временем жизни в часы
  • Как правильно использовать cacheTag() и updateTag() в Server Action?
  • Проверь, нужна ли мне директива use cache: private для компонента, который читает куки

Как установить cache-components

1Через Skills CLI (Vercel)

npx skills add laguagu/claude-code-nextjs-skills --skill cache-components -a claude-code

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

~/.claude/skills/cache-components/SKILL.md

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

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

Вопросы о cache-components

Как установить cache-components в Claude Code?

Выполни команду npx skills add laguagu/claude-code-nextjs-skills --skill cache-components -a claude-code, затем скилл будет доступен по пути ~/.claude/skills/cache-components/SKILL.md.

Что делает скилл cache-components?

Даёт экспертные советы по Next.js Cache Components и Partial Prerendering: работа с use cache, настройка времени жизни через cacheLife(), тегирование cacheTag(), инвалидация через updateTag(), оптимизация статического и динамического контента, отладка кэша.

Какая минимальная версия Next.js нужна для cache-components?

Next.js 16.4.1 и выше. Версии 16.0.0–16.4.0 содержат уязвимость в use cache — требуется обновление перед использованием скилла.

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

SKILL.md · MIT
---
name: cache-components
description: "Expert guidance for Next.js Cache Components and Partial Prerendering (PPR). Use when implementing 'use cache' directive, configuring cache lifetimes with cacheLife(), tagging cached data with cacheTag(), invalidating caches with updateTag()/revalidateTag(), optimizing static vs dynamic content boundaries, instant navigation validation, 'use cache: private', pass-through/interleaving patterns, GET Route Handler caching, debugging cache issues, and reviewing Cache Component implementations."
metadata:
  version: "1.0"
---

# Cache Components

Keep the project's caching mode unless migration is requested. Confirm the
installed Next.js version and `cacheComponents`/`partialPrefetching` configuration before applying
these patterns. Use Cache Components on next 16.4.5+: 16.0.0–16.4.0 allow
unauthenticated RCE through `use cache` functions returning typed arrays
(GHSA-673q-mjm6-r5xr; no workaround, upgrade even without such functions), and
releases through 16.4.4 can leak or poison cached output across users
(GHSA-rhh4-g77r-r9qj binary arguments, GHSA-vvgp-ww4w-46vf shared fallback
shells, GHSA-vc7v-qv4w-wrv8 and GHSA-mfr8-8qww-v76h root params).
Flag an affected install before cache work.

Read the relevant guide in `node_modules/next/dist/docs/` first (bundled since
16.2; in a monorepo, use the app's own `next` package). Web paths map to files
with numbered folders, so find them by name: `.../functions/cacheLife` is
`01-app/03-api-reference/04-functions/cacheLife.md`. Under `01-app/`, start
with `02-guides/migrating-to-cache-components.md`,
`01-getting-started/08-caching.md` and `02-guides/instant-navigation.md`.
Error pages under `/docs/messages` are not bundled; `next dev`/`next build`
print the fix options inline. Without local docs, use the
[official caching docs](https://nextjs.org/docs/app/getting-started/caching).
Exact exports and signatures are also in `node_modules/next/cache.d.ts`.
For static-output and staged-deferral questions in 16.4+, find the installed
`ensureStatic` route-segment reference and `navigation`/`prefetch` function
references by name.

The goal is a useful prerendered shell with freshness and authorization rules
that remain correct after mutations, deploys and client navigation.

## Facts older examples get wrong

- Next.js 16 enables the mode with top-level `cacheComponents: true`. It replaces
  `experimental.dynamicIO`, `experimental.useCache` and `experimental.ppr`;
  `cacheLife`/`cacheTag` import from `next/cache` without `unstable_`.
  In 16.4, set `partialPrefetching` explicitly: leaving it unset warns;
  recommended `create-next-app` defaults enable both flags.
- With it enabled, segment exports `dynamic`, `revalidate`, `fetchCache`,
  `dynamicParams` and `runtime` (even `'nodejs'`) are errors; only the default
  Node.js runtime is supported. `revalidate = N`
  becomes `cacheLife` (nearest or custom profile) inside `use cache`;
  `force-dynamic` and `fetchCache` are unnecessary; fetch
  `next: { revalidate, tags }` becomes `cacheLife`/`cacheTag` in a `use cache`
  function; request data goes under Suspense; `dynamicParams = false` becomes
  `notFound()` for unknown params.
- Existing `fetch` and `unstable_cache` caching still works as a separate layer,
  so do not mechanically rewrite every read. Its persistence across deployments
  and instances depends on retained/shared storage; self-hosted instances do not
  share it by default. `use cache` is in-memory by default; even a durable
  handler cannot reuse entries when the build/deployment ID changes.
- `generateStaticParams` must return at least one param: `[]` fails the build,
  and removing the export renders the route on every request.
- `revalidate: 0` or `expire` under 5 minutes makes a request-time hole instead
  of prerendered output; of the presets only `seconds` does. 16.3 adds `stale`
  thresholds (under 30 s: not prerendered; under 5 min: not in the App Shell).
- Synchronous `new Date()`, `Math.random()` or `crypto.randomUUID()` during
  prerender is an error: capture it in `use cache`, or defer with `await io()`
  (`next/cache`, 16.3+) or `await connection()` (`next/server`) under Suspense.
- `use cache: private` was experimental through 16.2. It runs at request time,
  stays out of the static shell and accepts no custom handler.
- `export const instant` (16.3; `unstable_instant` in 16.2) opts a segment into
  instant-navigation validation. Since 16.3, every Page/Default segment is
  implicitly validated in `next dev` only (dev overlay) at the default level;
  build validation requires `experimental.instantInsights.validationLevel`
  set to `experimental-error` or `experimental-manual-error` (16.2
  `unstable_instant` also validated at build). Test navigations with
  `@next/playwright` `instant()`. `instant = false` permits a blocking route;
  it does not clear synchronous-IO errors.

For whole-app adoption of Cache Components or Partial Prefetching, use the
official workflow skills listed in the installed `01-app/02-guides/ai-agents.md`
(from vercel/next.js `skills/`); the bundled `02-guides/migrating-to-cache-components.md`
and `adopting-partial-prefetching.md` cover the same steps.

## Shape of one route

`app/posts/page.tsx`, checked against next 16.3.8 with `cacheComponents: true`
(`tsc --noEmit`, `next build`, the action under `next start`). `@/lib/*` is
project code.

```tsx
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { cacheLife, cacheTag, updateTag } from 'next/cache'
import { insertPost, listPosts } from '@/lib/posts' // project code
import { requireEditor } from '@/lib/auth' // throws unless the session may edit

async function getPosts() {
  'use cache' // shared entry: no cookies/headers/searchParams inside
  cacheLife('hours')
  cacheTag('posts')
  return listPosts()
}

async function Theme() {
  const theme = (await cookies()).get('theme')?.value // request-time, outside the cache
  return <p>Theme: {theme ?? 'system'}</p>
}

async function addPost(formData: FormData) {
  'use server'
  await requireEditor()
  const title = String(formData.get('title') ?? '').trim()
  if (!title) return
  await insertPost(title)
  updateTag('posts') // Server Actions only; the next read waits for fresh data
}

export default async function Page() {
  const posts = await getPosts() // cached, so it can be part of the static shell
  return (
    <>
      <ul>{posts.map((p) => <li key={p.id}>{p.title}</li>)}</ul>
      <Suspense fallback={<p>Theme: …</p>}><Theme /></Suspense>
      <form action={addPost}><input name="title" /><button>Add</button></form>
    </>
  )
}
```

## Decide the boundary

- Cache reusable results when the product's freshness and data policy permit.
  Static content needs no directive just to be static.
- A plain `use cache` scope cannot read cookies, headers, searchParams or call
  `connection()`, including indirectly through helpers. Read those outside
  and pass authorized, serializable values.
  Account/tenant IDs must participate in the cache key when output depends on them.
  On a dynamically rendered route, the `next-request-in-use-cache` error can
  pass `next build` and surface only under `next start`.
- Keep uncached I/O and request-only content below appropriate Suspense
  boundaries. Suspense supplies fallback UI; it does not itself make synchronous
  work dynamic.
- Evaluate private/remote variants against installed docs and deployment
  handlers. Private caching is not a compliance guarantee; remote caching is not
  a consistency protocol.

## Define freshness and invalidation

Choose lifetimes from actual acceptable staleness. Named profiles can be
overridden by the project; read its config before assuming a duration.

Use tags when invalidation must reach the same entity across routes, path
invalidation for route-specific output, or expiry where that meets the contract.
Authenticate, authorize and validate before mutations. Invalidate only affected
cached data:

- `updateTag`: immediate expiry/read-your-writes, Server Actions only.
- `revalidateTag(tag, 'max')`: stale-while-revalidate on a later visit.
- `revalidateTag(tag, { expire: 0 })`: immediate expiry where a webhook/Route
  Handler needs it. The one-argument form is deprecated.

These tag APIs can also apply to tagged fetch data; their availability does not
by itself mean Cache Components is enabled.

## Read for the problem

- [API boundaries](REFERENCE.md): keys, serialization, lifetimes, handlers and route APIs.
- [Composition](PATTERNS.md): tenant isolation, nested caches, pass-through and dynamic params.
- [Troubleshooting](TROUBLESHOOTING.md): diagnose blocking, stale or inconsistent output.

Run the production build, then exercise cold/direct navigation, client
navigation, the relevant mutation and subsequent read under `next start`.
Check tenant isolation and multi-instance invalidation when applicable.
A passing build cannot establish those behaviors.

© laguagu · MIT · laguagu/claude-code-nextjs-skills

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

Все скиллы по теме «Фронтенд и UI» →

Сначала — cache-components от других авторов.

cache-components sangrokjung Скилл учит агента применять Cache Components и Partial Prerendering в Next.js: директива 'use cache', настройка времени жизни через cacheLife(), инвалидация по тегам. CX Codex +1 ★ 880звёзд репо next-cache-components официальный Vercel Labs Скилл next-cache-components для Codex помогает настраивать Cache Components в Next.js 16+. Он включается при работе с PPR, кэшированием и переходе с unstable_cache. CX Codex GP ChatGPT +1 4установок next-cache-components-optimizer vercel Скилл next-cache-components-optimizer ускоряет отрисовку статического каркаса страниц в Next.js. Скилл находит медленные Suspense-границы через падающий e2e-тест Playwright и чинит навигацию. CX Codex +1 22 000установок nextjs-cache-architecture mohamed-hossam1 Скилл nextjs-cache-architecture выстраивает архитектуру кеширования для Next.js 16+ App Router. Помогает внедрить директиву "use cache", собрать типизированный реестр тегов и настроить границы Suspense. CX Codex +1 5 100установок sanity-live-cache-components sanity-io Скилл sanity-live-cache-components связывает next-sanity с кэшируемыми компонентами Next.js: один общий 'use cache'-барьер, sanityFetch и живая перевалидация через <SanityLive>. CX Codex +1 602установок react-fetch-cache-patterns pproenca Скилл react-fetch-cache-patterns с 48 правилами для масштабируемой выборки и кеширования данных в React: от параллелизма запросов до защиты бэкенда, префетча и восстановления после ошибок. CX Codex +1 180установок react-server-components patterns.dev Скилл объясняет React Server Components: какие компоненты рендерить на сервере и где ставить 'use client'. Пригодится в Next.js App Router. CX Codex +1 1 000установок

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

Весь набор →
supabase-postgres-best-practices Скилл supabase-postgres-best-practices помогает агенту проектировать схемы и писать SQL с учётом правил Supabase для Postgres. Подключайте его до изменений базы и при разборе проблем с запросами, подключениями или RLS. CX Codex +1 146установок nextjs-shadcn Скилл nextjs-shadcn для Claude Code и Codex настраивает интерфейсы Next.js на базе shadcn/ui. Агент подключает его при сборке и редизайне страниц, компонентов и дизайн-систем. CX Codex +1 861установок next-best-practices Скилл next-best-practices для Claude Code подсказывает практики Next.js App Router при написании и проверке кода. Помогает разбирать ошибки гидратации, границы RSC и проблемы с данными. CX Codex +1 286установок postgres-semantic-search Скилл postgres-semantic-search для Claude Code настраивает поиск и извлечение данных в PostgreSQL. Помогает собрать семантический или гибридный поиск, оценить качество результатов и разобраться со слабыми совпадениями. CX Codex +1 227установок ai-sdk-6 Скилл ai-sdk-6 для работы с проектами на Vercel AI SDK v6. Помогает строить агентов, чат-ботов, инструменты и потоки структурированного вывода, если кодовая база уже на версии 6. CX Codex +1 218установок ai-app Скилл ai-app для Claude Code настраивает фулстек-приложения на Next.js с AI SDK и shadcn/ui. Запускается при создании чат-ботов, панелей управления агентами и ИИ-интерфейсов. CX Codex +1 198установок nextjs-chatbot Скилл nextjs-chatbot помогает собрать веб-чат на Next.js: подтверждение вызовов инструментов, сохранённая история, отрисовка результатов, подсказки и встраиваемый виджет. CX Codex +1 161установок ai-sdk Проверяет версию Vercel AI SDK в проекте и направляет агента к нужной документации. Включается при запросах о потоковом выводе, useChat, агентах и вызове инструментов. CX Codex +1 149установок

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

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