Skip to main content
skill CX Codex

cache-components · laguagu — Claude Code skill: Next.js caching

A skill for mastering Next.js Cache Components and Partial Prerendering in version 16.4+. Advises on the use cache directive, setting cache lifetime with cacheLife(), tagging data with cacheTag(), and invalidating via updateTag().

MIT 222 installs ★ 74 updated 2026-11-14

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add laguagu/claude-code-nextjs-skills --skill cache-components -a claude-code
Open on GitHub

What cache-components does

This skill covers Next.js Cache Components and Partial Prerendering (PPR), which replace the older experimental flags dynamicIO, useCache, and ppr. Compatible with Next.js 16.4.1+. Versions 16.0.0–16.4.0 contain a vulnerability in the use cache feature that allows unauthenticated remote code execution when typed arrays are returned (GHSA-673q-mjm6-r5xr)—upgrade before proceeding.

The skill helps define boundaries between cacheable and dynamic content, configure cache lifetime via cacheLife(), tag data with cacheTag(), and invalidate via updateTag() or revalidateTag(). It explains use cache: private (runs at request time, excluded from the static shell), GET Route Handler caching, and patterns like pass-through and interleaving. It can also debug cache issues and review implementations.

The skill references documentation bundled in node_modules/next/dist/docs/ (since 16.2) and type definitions in node_modules/next/cache.d.ts. Before working with it, verify your Next.js version and confirm that cacheComponents and partialPrefetching are explicitly enabled in your config.

What it helps with

  • set up component caching in Next.js 16.4+
  • configure cache lifetime with cacheLife() and lifecycle profiles
  • tag data with cacheTag() and invalidate via updateTag()
  • establish correct boundaries between static and dynamic content
  • debug cache and Partial Prerendering issues

Example prompts for the agent

  • Implement a use cache function that fetches a post list with an hourly lifetime
  • Show me the right way to use cacheTag() and updateTag() in a Server Action
  • Do I need use cache: private for a component that reads cookies?

How to install cache-components

1Skills CLI (Vercel)

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

2Manually: put the files in place

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

Copy the whole skill folder; for one project use .claude/skills/cache-components/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about cache-components

How do I install cache-components in Claude Code?

Run npx skills add laguagu/claude-code-nextjs-skills --skill cache-components -a claude-code. The skill will be available at ~/.claude/skills/cache-components/SKILL.md.

What does the cache-components skill do?

It provides expert guidance on Next.js Cache Components and Partial Prerendering: using use cache, setting cache lifetime with cacheLife(), tagging with cacheTag(), invalidating with updateTag(), optimizing static and dynamic boundaries, and troubleshooting cache problems.

What is the minimum Next.js version required?

Next.js 16.4.1 and later. Versions 16.0.0–16.4.0 have a security issue in use cache—you must upgrade before using this skill.

Source text

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

Similar skills

All skills for Frontend and UI →

cache-components by other authors comes first.

cache-components sangrokjung The skill teaches the agent to apply Cache Components and Partial Prerendering in Next.js: 'use cache' directive, cache lifetimes with cacheLife(), tag-based invalidation. CX Codex +1 ★ 880repo stars next-cache-components official Vercel Labs next-cache-components is a Codex skill for Cache Components in Next.js 16+. It activates for PPR work, caching changes, or migrations from unstable_cache. CX Codex GP ChatGPT +1 4installs next-cache-components-optimizer vercel next-cache-components-optimizer optimizes Next.js App Shell UI on hard and soft navigations. It sets up failing Playwright instant() checks and guides routes to green. CX Codex +1 22,000installs nextjs-cache-architecture mohamed-hossam1 nextjs-cache-architecture structures caching architecture in Next.js 16+ App Router projects. It sets up the "use cache" directive, a typed tag registry, and Suspense boundaries. CX Codex +1 5,100installs sanity-live-cache-components sanity-io sanity-live-cache-components connects next-sanity to Next.js Cache Components: sanityFetch behind one shared 'use cache' boundary, with <SanityLive> keeping cached pages fresh. CX Codex +1 602installs react-fetch-cache-patterns pproenca react-fetch-cache-patterns — a skill with 48 rules for scalable data fetching and caching in React: request orchestration, backend protection, prefetching, error resilience. CX Codex +1 180installs react-server-components patterns.dev Teaches React Server Components: which components belong on the server and where 'use client' goes. Useful in Next.js App Router. CX Codex +1 1,000installs

From the same set13

The whole set →
supabase-postgres-best-practices The supabase-postgres-best-practices skill guides agents through Postgres schema and SQL work using Supabase-maintained rules. Load it before database changes or when investigating query, connection, and RLS issues. CX Codex +1 146installs nextjs-shadcn nextjs-shadcn — a skill for Claude Code that guides Next.js and shadcn/ui development. Activates when building or refining pages, presets, layouts and design system components. CX Codex +1 861installs next-best-practices The next-best-practices Claude Code skill applies Next.js App Router practices while writing or reviewing code. It covers hydration bugs, RSC boundaries, async APIs, and data handling. CX Codex +1 286installs postgres-semantic-search The postgres-semantic-search Claude Code skill builds and tunes PostgreSQL retrieval. It covers semantic and hybrid search, evaluation, and troubleshooting weak results. CX Codex +1 227installs ai-sdk-6 ai-sdk-6 — a skill for projects already on Vercel AI SDK v6. Covers building agents, chatbots, tool integrations, streaming responses and structured output with patterns specific to the v6 API. CX Codex +1 218installs ai-app A skill for Claude Code sets up full-stack Next.js AI applications with AI SDK and shadcn/ui. Activates when generating chatbots, agent dashboards, and custom AI tools. CX Codex +1 198installs nextjs-chatbot nextjs-chatbot guides a production web chat in Next.js: tool approval, saved conversations, rendered tool results, follow-up suggestions and an embeddable widget. CX Codex +1 161installs ai-sdk Identifies the installed Vercel AI SDK major version and routes to matching API docs. Activates when working with generateText, streamText, useChat, or tools. CX Codex +1 149installs

Project sponsors

Companies that keep this analytics open