Caching and revalidation
Caching stores the result of work (a database query, an API call, a rendered component) so the next request can reuse it instead of doing the work again. Done right, it makes pages load in milliseconds and keeps your database calm under traffic.
Next.js 16 uses an explicit caching model called Cache Components: nothing is cached unless you say so, with the 'use cache' directive.
Turn on Cache Components
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
cacheComponents: true,
};
export default nextConfig;(Apps that don't enable this use the older model, based on fetch options and route segment config. You'll see both in the wild.)
'use cache': cache a function's result
Put the directive at the top of an async function:
// app/lib/data.ts
import { cacheLife } from 'next/cache';
export async function getProducts() {
'use cache';
cacheLife('hours'); // how long the result stays fresh
return db.query('SELECT * FROM products');
}Every component that calls getProducts() shares the cached result. The function's arguments become part of the cache key, so getUser(1) and getUser(2) are cached separately.
Cache a whole component or page
// app/page.tsx
import { cacheLife } from 'next/cache';
export default async function Page() {
'use cache';
cacheLife('hours');
const posts = await getLatestPosts();
return <ul>{posts.map((p) => <li key={p.id}>{p.title}</li>)}</ul>;
}Put 'use cache' at the top of a file and every exported function in it is cached.
cacheLife: how long?
| Profile | stale |
revalidate |
expire |
|---|---|---|---|
seconds |
30s | 1s | 60s |
minutes |
5m | 1m | 1h |
hours |
5m | 1h | 1d |
days |
5m | 1d | 1w |
weeks |
5m | 1w | 30d |
max |
5m | 30d | 1y |
- stale: how long the browser can use it without checking
- revalidate: after this, the next request gets the cached value and triggers a background refresh
- expire: after this with no traffic, the next request waits for fresh data
You can also pass a custom object: cacheLife({ stale: 60, revalidate: 300, expire: 3600 }).
Static shell + streaming dynamic parts
With Cache Components, Next.js pre-renders as much of each page as it can into a static shell that loads instantly, and streams the request-specific parts in:
import { Suspense } from 'react';
import { cookies } from 'next/headers';
export default function ProductPage() {
return (
<>
<ProductInfo /> {/* 'use cache' → part of the static shell */}
<Suspense fallback={<p>Loading your price…</p>}>
<PersonalisedPrice /> {/* reads cookies → streamed per request */}
</Suspense>
</>
);
}
async function ProductInfo() {
'use cache';
const p = await getProduct('mug');
return <h1>{p.name}</h1>;
}
async function PersonalisedPrice() {
const tier = (await cookies()).get('tier')?.value ?? 'standard';
return <p>Your price: {tier === 'gold' ? '$8' : '$9'}</p>;
}Uncached or runtime data (cookies(), headers(), searchParams, uncached fetches) belongs inside <Suspense>. In development, Next.js shows a "blocking route" hint if you forget.
On-demand revalidation with tags
Tag cached data, then invalidate it when the data changes:
// app/lib/data.ts
import { cacheTag, cacheLife } from 'next/cache';
export async function getPosts() {
'use cache';
cacheTag('posts');
cacheLife('days');
return db.post.findMany();
}// app/actions.ts
'use server';
import { updateTag, revalidateTag } from 'next/cache';
export async function publishPost(formData: FormData) {
await db.post.create({ data: { title: String(formData.get('title')) } });
updateTag('posts'); // expire now: the author sees their post immediately
}
export async function importPostsFromCMS() {
await syncFromCMS();
revalidateTag('posts', 'max'); // stale-while-revalidate: visitors get fast (old) data while it refreshes
}updateTag |
revalidateTag |
|
|---|---|---|
| Where | Server Actions only | Server Actions and Route Handlers |
| Behaviour | Expires immediately; the next read waits for fresh data | Serves stale data while refreshing in the background |
| Best for | "I just changed this, show me" | CMS webhooks, catalogue updates |
revalidatePath('/blog') revalidates everything rendered for a path.
The mental model in one picture
Request ─▶ Static shell (pre-rendered, cached) ← instant
├─ 'use cache' components (cached data) ← fast, refreshed by cacheLife / tags
└─ <Suspense> holes (cookies, user data) ← streamed per requestHere's stale-while-revalidate demonstrated in the browser. The "cache" serves the old value instantly while refreshing in the background:
Practice (in your project)
- Enable
cacheComponentsinnext.config.ts. - Create
getQuote(), which fetches a random quote from an API, cached with'use cache'andcacheLife('minutes'). Show it on the home page and reload a few times. It stays the same. - Tag it with
cacheTag('quote'), and add a Server Action button that callsupdateTag('quote'). Clicking it should show a new quote.
1.In Next.js 16 with Cache Components, is fetch data cached by default?
2.You want visitors to keep getting fast pages while a product catalogue refreshes in the background. Which do you call?