Next.js use cache: App Router caching guide
- Authors
- Name
- Hamza Rahman
- Published on
- -12 mins read
This guide explains how caching works in the Next.js 16.5 App Router and builds a small app with a cached data read, on-demand invalidation, a timed refresh, and a part that stays dynamic.
Checked on December 4, 2026 with Next.js 16.5.0 (released December 2, 2026), React 19.3.1 and Node.js 26.14.0. The example was built and run with next build and next start.
The mental model
Next.js calls the current model Cache Components. New create-next-app projects have it on by default since Next.js 16.4. Existing apps opt in through next.config.ts:
// next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
export default nextConfig
Set partialPrefetching explicitly to avoid a logged warning. It controls link prefetching and isn't needed for the rest of this post. Cache Components requires the Node.js runtime and rejects every runtime export, including export const runtime = 'nodejs' as well as 'edge'. Remove them before you enable the flag. If you deploy somewhere else, such as Cloudflare Workers, check your adapter's support before you enable it.
With cacheComponents on, every piece of a page falls into one of three groups:
- Static. Plain markup and synchronous work. Next.js prerenders it.
- Cached. Async work inside a function or component marked
'use cache'. Next.js prerenders it too, as long as its lifetime is not too short. - Dynamic. Uncached async work, or anything that reads the request. It goes inside
Suspenseand streams in when a visitor asks for the page.
Nothing is cached until you opt in. Next.js prerenders the static parts, cached parts and Suspense fallbacks into a static shell that it sends first, then streams the dynamic parts. That is Partial Prerendering, the default under this flag. The old experimental.ppr option is gone.
Set up a slow data source
Create the app:
npx create-next-app@16.5.0 next-cache --ts --app --no-tailwind --no-eslint --no-src-dir --import-alias '@/*' --use-npm --yes
cd next-cache
The fake backend takes 1.5 seconds per read and counts its reads:
// slow-api.mjs
import { createServer } from 'node:http'
import { setTimeout as sleep } from 'node:timers/promises'
let price = 100
const reads = { product: 0, rate: 0 }
createServer(async (req, res) => {
const { pathname, searchParams } = new URL(req.url, 'http://localhost')
if (pathname === '/set-price') {
price = Number(searchParams.get('value'))
return res.end('ok')
}
const key = pathname.slice(1)
if (!(key in reads)) return res.writeHead(404).end()
await sleep(1500)
reads[key]++
console.log('read', key, reads[key])
res.end(JSON.stringify({ price, rate: 1.1, read: reads[key] }))
}).listen(4000)
Run node slow-api.mjs in a second terminal. It must be running during next build, because the build fills the cache.
Cache a read and tag it
// lib/data.ts
import { cacheLife, cacheTag } from 'next/cache'
const API = 'http://localhost:4000'
export async function getProduct(): Promise<{ price: number; read: number }> {
'use cache'
cacheLife('hours')
cacheTag('product')
const res = await fetch(`${API}/product`)
return res.json()
}
export async function setPrice(value: number) {
await fetch(`${API}/set-price?value=${value}`)
}
'use cache' stores the function's result. The arguments, and any values captured from an outer scope, become part of the cache key. cacheLife sets the lifetime and cacheTag gives you a name to invalidate.
Arguments and return values must be serializable. Plain objects, arrays, Date, Map and Set are fine; class instances are not.
Mix cached and dynamic parts on one page
// app/page.tsx
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { getProduct } from '@/lib/data'
import { savePrice } from './actions'
async function ProductCard() {
const { price, read } = await getProduct()
return <p>{`Keyboard: ${price} (read ${read})`}</p>
}
async function Greeting() {
const name = (await cookies()).get('name')?.value ?? 'guest'
return <p>{`Hello, ${name}`}</p>
}
export default function Page() {
return (
<main>
<h1>Shop</h1>
<ProductCard />
<Suspense fallback={<p>Loading greeting</p>}>
<Greeting />
</Suspense>
<form action={savePrice}>
<input name="price" type="number" defaultValue={120} />
<button>Save price</button>
</form>
</main>
)
}
ProductCard needs no Suspense, because its data is cached at build time. Greeting reads a cookie, so it waits for a real request. Reading cookies() no longer makes the whole route dynamic.
Invalidate it from a server action
// app/actions.ts
'use server'
import { updateTag } from 'next/cache'
import { setPrice } from '@/lib/data'
export async function savePrice(formData: FormData) {
await setPrice(Number(formData.get('price')))
updateTag('product')
}
updateTag expires the tag at once, so the next read waits for fresh data. Use it when people must see their own change. It only works in server actions. Calling it from a route handler fails with a 500 and this error in the server log:
Error: updateTag can only be called from within a Server Action. To invalidate
cache tags in Route Handlers or other contexts, use revalidateTag instead.
For a webhook, use revalidateTag with a profile:
// app/api/price-webhook/route.ts
import { revalidateTag } from 'next/cache'
export async function POST() {
revalidateTag('product', 'max')
return Response.json({ ok: true })
}
With 'max', the next visitor gets the old value while Next.js refreshes it in the background. Pass the second argument: the one-argument form is deprecated and fails type checking with Expected 2 arguments, but got 1. Outside server actions, pass an object with expire: 0 when stale data is not acceptable.
Protect a real webhook. Anyone who can call this one can force a refresh.
Refresh on a timer
// app/rate/page.tsx
import { cacheLife } from 'next/cache'
async function RateCard() {
'use cache'
cacheLife({ stale: 300, revalidate: 10, expire: 3600 })
const res = await fetch('http://localhost:4000/rate')
const { rate, read } = await res.json()
return <p>{`Rate: ${rate} (read ${read})`}</p>
}
export default function Page() {
return <RateCard />
}
All three values are in seconds:
stale: how long the browser's client cache can reuse the result without asking the server.revalidate: after this, the next request gets the old value and starts a background refresh.expire: after this long without traffic, the next request waits for fresh data.
You can also use a preset: seconds, minutes, hours, days, weeks or max. Without cacheLife you get the default profile, which revalidates after 15 minutes and never expires.
Very short lifetimes are left out of the static shell. That happens when revalidate is 0, expire is under 5 minutes, or stale is under 30 seconds. Those parts, including the seconds preset, run at request time and need Suspense.
Build it
For comparison, add a page that does the same fetch without 'use cache':
// app/uncached/page.tsx
import { Suspense } from 'react'
async function ProductCard() {
const res = await fetch('http://localhost:4000/product')
const { price, read } = await res.json()
return <p>{`Keyboard: ${price} (read ${read})`}</p>
}
export default function Page() {
return (
<Suspense fallback={<p>Loading product</p>}>
<ProductCard />
</Suspense>
)
}
Build and start the app with the slow API still running:
npm run build && npm start
The build prints this route table:
Route (app) Revalidate Expire
┌ ◐ / 1h 1d
├ ○ /_not-found
├ ƒ /api/price-webhook
├ ○ /rate 10s 1h
└ ◐ /uncached
○ (Static) prerendered as static content
◐ (Partial Prerender) prerendered as static HTML with dynamic server-streamed content
ƒ (Dynamic) server-rendered on demand
These timings come from three clean next build and next start runs on one busy Linux machine. They are full curl response times, and the action was a no-JS form POST, so the browser's client cache wasn't tested. Read them as "waits for the 1.5 s backend" or "does not wait", not as a benchmark.
| Request | Total time, 3 runs | Waited for backend |
|---|---|---|
/uncached, three requests per run | 1.57 to 2.37 s | Yes, every time |
/, three requests per run | 0.02 to 0.26 s | No |
/rate, 12 s later (stale value served) | 0.01 to 0.03 s | No |
/, backend price changed, nothing invalidated | 0.02 to 0.08 s | No, old price |
Server action POST with updateTag | 1.54 to 1.59 s | Yes, new price |
First / after the action | 1.57 to 1.63 s | Yes, new price |
Second / after the action | 0.03 to 0.09 s | No |
First / after the webhook ('max') | 0.04 to 0.07 s | No, old price |
/ about 3 s later | 0.02 to 0.10 s | No, new price |
The action re-renders the current route in its response, which accounts for the first backend read. The first GET / after it read the backend again in all three runs, and the second came from cache. On a slow source, expect the first visitor after updateTag to wait too.
There is also an open race condition. If a page regeneration starts before updateTag and finishes after it, Next.js can store the old render as fresh (#102637). The issue reports the page staying stale until its revalidate period passes or the tag is invalidated again. In a related race, a request after updateTag can join a 'use cache' read that was already running and get old data once (#100345). Both issues were open on December 4, 2026, with fix PRs not yet merged. On 16.5.0, calling updateTag during a timed refresh (revalidate: 5) gave one stale page load in three of three tries. The race isn't limited to short timers: #102637 reproduces it with a 15 minute period.
What happens when you mix them wrong
Put the cookie read inside a cached function:
async function getGreeting() {
'use cache'
const name = (await cookies()).get('name')?.value ?? 'guest'
return `Hello, ${name}`
}
The build fails, with or without Suspense around it:
Error: Route "/broken": `cookies()` can't be read inside `"use cache"`. Read it
outside the cached function and pass what you need as an argument.
Learn more: https://nextjs.org/docs/messages/next-request-in-use-cache
Read the cookie outside and pass the value in:
async function Greeting() {
const name = (await cookies()).get('name')?.value ?? 'guest'
return <p>{await getGreeting(name)}</p>
}
async function getGreeting(name: string) {
'use cache'
return `Hello, ${name}`
}
Keep Greeting inside Suspense. Each distinct value makes its own cache entry, so pass a small value such as a locale, not a whole session object.
If refactoring isn't practical, 'use cache: private' can read cookies, but its results aren't stored on the server across production requests.
A passing build doesn't catch every case. On a dynamically rendered route, such as one that calls await connection() first, the error can pass next build and appear under next start. Request those pages in your tests.
The opposite mistake is reading a cookie with no Suspense. That also fails the build (output shortened):
Error: Route "/broken": Next.js encountered uncached or runtime data during prerendering.
Ways to fix this:
- [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
- [cache] For uncached data (`fetch`, database calls): cache the access with `"use cache"`
- [block] Set `export const instant = false` to allow a blocking route
Run next build --debug-prerender for better stack traces.
Coming from Next.js 13 to 15
| Old code | With Cache Components |
|---|---|
fetch cached by default (13, 14) | Not cached. The default changed in 15 |
fetch with cache: 'force-cache' | Still works. Prefer fetch inside 'use cache' |
next.revalidate on fetch | cacheLife |
next.tags on fetch | cacheTag |
unstable_cache(fn, keys, options) | Still works. Prefer 'use cache' with cacheLife and cacheTag |
export const revalidate = 3600 | Remove it, use 'use cache' and cacheLife('hours') |
export const dynamic = 'force-dynamic' | Remove it, dynamic is the default |
export const dynamic = 'force-static' | Remove it, use 'use cache' and cacheLife('max') |
export const fetchCache | Remove it, cache at the data source |
revalidateTag(tag) | updateTag(tag) in actions, or revalidateTag(tag, 'max') |
revalidatePath(path) | Unchanged |
unstable_noStore() | Remove it, or use await connection() inside Suspense |
experimental.ppr, experimental_ppr | Removed, use cacheComponents |
experimental.dynamicIO, experimental.useCache | cacheComponents |
Leftover revalidate, dynamic and fetchCache exports are errors, not warnings. This is the message for revalidate:
Error: Route segment config "revalidate" is not compatible with
`nextConfig.cacheComponents`. Please remove it.
The migration guide lets you move one route at a time with export const instant = false. If you leave the flag off, use the previous caching model docs instead.
Where the cache lives
By default, runtime entries are in memory, per server instance. They survive between requests on one long-running server and are lost on a new deploy. On serverless hosts they usually don't survive between requests, though prerendered output does.
This differs from unstable_cache and cached fetch, which persist across deployments. If you need shared or durable storage, use 'use cache: remote' with a cache handler. Since 16.5, Turbopack builds can reuse those remote entries across deploys when the cached code and its dependencies have not changed.
When to use this
- Same for everyone and slow to load:
'use cache'with an explicitcacheLife. - Changed by your own users: add
cacheTag, and callupdateTagin the action. - Changed by another system:
cacheTag, andrevalidateTag(tag, 'max')in a webhook. - Depends on the request: leave it uncached inside
Suspense, or pass a small value into a cached function.
For client-side events on the links between these pages, see Next.js Link onClick.
References
Related articles
Vite 8 and Rolldown: upgrade guide
Upgrade a Vite 5, 6 or 7 project to Vite 8: what Rolldown and Oxc replace, which config options break, how to check plugins, and measured build times.
Nextjs Link onClick: Run Code, Redirect, and Handle Forms
How to use the onClick prop on the Next.js Link component to run code before navigation, redirect programmatically, and use preventDefault, with App Router and Pages Router examples in JavaScript and TypeScript.
What an AI coding model costs per solved task
Turn per-million-token prices into cost per attempt and cost per solved task with small JavaScript functions, including caching, retries and review time.

