nextjs-caching
Skill2 starsChanged 5 months agoMITView on GitHub
Next.js Cache Components and Partial Prerendering (PPR). Use when implementing 'use cache' directive, cacheLife() profiles, cacheTag()/updateTag() invalidation, PPR static shells with dynamic streaming, or debugging cache issues. Auto-activates in projects with cacheComponents: true in next.config.ts.
1 other project uses a version of this.
Adopted by
Most recently taken up by
- goncy/skillstheir own version, first seen Mar 10, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- goncy/skills★ 15same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository5 other files it gives its agents.
- AGENTS.mdAGENTS.md
- for-copilot/copilot-instructions.mdCopilot instructions
- nextjs-coreSkill
- nextjs-react-best-practicesSkill
- nextjs-seo-performanceSkill
The file
Files
Next.js Caching (Cache Components)
Requires:
cacheComponents: trueinnext.config.ts(Next.js 16).
Project Detection
grep -r "cacheComponents" next.config.* 2>/dev/nullEnable
// next.config.ts
const nextConfig: NextConfig = { cacheComponents: true };
export default nextConfig;Decision Steps
- Does component fetch data? No → skip. Yes → continue.
- Depends on
cookies()/headers()/searchParams? No → step 3. Yes → step 4. - Same data for all users? Yes →
'use cache'+cacheTag()+cacheLife(). No →<Suspense>. - Can extract runtime data as args? Yes → pass outside cache. No →
'use cache: private'(last resort).
Core APIs
'use cache' Directive
async function BlogPosts() {
'use cache'; // MUST be first statement; function MUST be async
cacheTag('posts');
cacheLife('hours');
return await db.posts.findMany();
}cacheLife() Profiles
cacheLife('seconds'); // stale:30s | revalidate:1s | expire:1m
cacheLife('minutes'); // stale:5m | revalidate:1m | expire:1h
cacheLife('hours'); // stale:5m | revalidate:1h | expire:1d
cacheLife('days'); // stale:5m | revalidate:1d | expire:1w
cacheLife('weeks'); // stale:5m | revalidate:1w | expire:30d
cacheLife('max'); // stale:5m | revalidate:30d | expire:1y
// Custom:
cacheLife({ stale: 60, revalidate: 3600, expire: 86400 });By content type: news → seconds, blog/docs → hours, marketing → days, legal → max
cacheTag() + Invalidation
// Tag
async function ProductList({ category }: { category: string }) {
'use cache';
cacheTag('products', `category-${category}`);
cacheLife('hours');
return await db.products.findMany({ where: { category } });
}
// Invalidate — Server Action (immediate, read-your-own-writes)
'use server';
export async function createProduct(formData: FormData): Promise<void> {
await db.products.create({ data: parseFormData(formData) });
updateTag('products');
}
// Invalidate — Route Handler / webhook (stale-while-revalidate)
export async function POST(request: Request) {
const { tag } = await request.json();
revalidateTag(tag, 'max'); // two-arg form — single arg is DEPRECATED
return Response.json({ revalidated: true });
}Server Actions vs Data Fetching (CRITICAL)
// ❌ WRONG: Server Action for data fetch
'use server';
export async function getProducts() { return await db.products.findMany(); }
// ✅ CORRECT: cached data function
export async function getProducts() {
'use cache';
cacheTag('products');
cacheLife('hours');
return await db.products.findMany();
}
// ✅ CORRECT: Server Action for mutation only
'use server';
export async function createProduct(formData: FormData): Promise<void> {
await db.products.create({ data: formData });
updateTag('products');
}PPR Pattern
export default async function ProductPage({ params }) {
const { id } = await params;
return (
<>
<ProductHeader /> {/* static */}
<CachedProductDetails id={id} /> {/* 'use cache' — in static shell */}
<Suspense fallback={<Skeleton />}>
<UserCart /> {/* dynamic — streams after load */}
</Suspense>
</>
);
}
async function CachedProductDetails({ id }: { id: string }) {
'use cache';
cacheTag(`product-${id}`);
cacheLife('hours');
const product = await db.products.findUnique({ where: { id } });
return <ProductInfo product={product} />;
}Runtime Data Pattern (cookies inside cache)
// ❌ WRONG: cookies() inside 'use cache'
async function UserData() {
'use cache';
const cookieStore = await cookies(); // ERROR
}
// ✅ CORRECT: extract outside, pass as arg
async function UserDataWrapper() {
const cookieStore = await cookies();
const userId = cookieStore.get('userId')?.value;
return <CachedUserData userId={userId} />;
}
async function CachedUserData({ userId }: { userId: string }) {
'use cache';
cacheTag(`user-${userId}`);
cacheLife('minutes');
return await getUser(userId);
}Review Checklist
cacheComponents: trueinnext.config.ts- All
'use cache'functions areasync 'use cache'is first statementcacheTag()present (enables targeted invalidation)cacheLife()present (don't rely on defaults)cookies()/headers()NOT inside'use cache'scope- Server Actions call
updateTag()after mutations - Dynamic components wrapped in
<Suspense> revalidateTag(tag, profile)— two-arg form (not deprecated single-arg)- Server Actions return
void, never used for data fetching
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

