Caching in Next.js 16, explained by the errors you’ll hit
Make a Next.js 16 app fast with Cache Components: cache data with “use cache”, refresh it the moment it changes with updateTag, keep per-visitor parts fresh with Suspense, and understand every error the build throws at you. Tested on a fresh project before publishing.
Tested step by step on with Next.js 16.4.6 and Prisma 7.10.1
Next.js 16 has a new way to make pages fast, called Cache Components. A fresh create-next-app project already has it switched on — which is why the first database read you write can fail npm run build with an error that seems to come from nowhere. This guide explains how it works by building on a real app, and by meeting each error on purpose, so you know exactly what it means when you see it in your own project.
You’ll make a task list load instantly from a cache, show it on a second page, fix the stale data that caching causes, and add a per-visitor setting that stays fresh. Every step was run on a fresh create-next-app project and a fresh shadcn init project, with Next.js 16.4 and Prisma 7.10, and every error message below was reproduced by breaking the app on purpose.
Before you start
- The tasks app from Next.js 16 + Prisma 7 + Postgres, steps 1 to 11. It has a
/taskspage that lists, adds, ticks and deletes tasks from a database. This guide changes that app. - Run every command from the project’s folder, and keep
npm run devrunning in its own terminal while you try things.
1. Switch Cache Components on
Open next.config.ts. A create-next-app project already has these two lines; a shadcn init project doesn’t. If they’re missing, add them inside the nextConfig object:
cacheComponentsturns on the caching this guide is about, and the"use cache"directive. Without it, any"use cache"fails the build with “To use "use cache", please enable the feature flagcacheComponentsin your Next.js config.”partialPrefetchingmakes links prefetch the parts of a page that can be prepared ahead of time. Set it explicitly: with onlycacheComponents, every build warns “cacheComponentsis enabled without a correspondingpartialPrefetchingoption.”
Restart npm run dev after changing next.config.ts.
2. Read what the build tells you
At the end, the build prints every route with a symbol in front of it. They’re the quickest way to see how each page is served:
○Static: the whole page was rendered at build time and is served instantly, as plain HTML.◐Partial Prerender: a static outline is served instantly, and the parts that need a real request stream in a moment later.ƒDynamic: rendered on the server on every request.
Right now /tasks is ◐. In the Prisma guide its list calls await connection() inside <Suspense>, which says “read the database on every request”: the heading and the form are static, the list streams in. That’s always correct — but every visit pays for a database query. Caching is how you stop paying for work you’ve already done.
3. Cache the task list
Move the query into a function of its own, and mark it "use cache". Create lib/tasks.ts:
"use cache"(the first line of the function) tells Next.js to keep what the function returns and hand it back next time instead of running it again.cacheLife("hours")says how long it may be kept: refreshed in the background after an hour, thrown away after a day. Step 8 explains the choices.cacheTag("tasks")labels the entry, so you can throw it away the moment the tasks change (step 5).cachedAtis there so you can see the cache working: it records when the list was really read from the database.
Now let the page use it. Replace app/tasks/page.tsx — it’s the same page, with connection() gone and the list coming from getTasks():
/tasks is now ○ Static, with two new columns beside it: Revalidate 1h and Expire 1d. That’s your cacheLife("hours"), and the list is part of the HTML the build produced. Open http://localhost:3000/tasks (dev server running) and reload a few times: “List cached at” doesn’t change, because the database isn’t being asked again. Add a task: it appears, and the time changes — the action’s revalidatePath("/tasks") threw the old copy away.
4. Show the count on another page
Real apps show the same data in more than one place. The home page only needs two numbers, so give it a cheaper query of its own, cached and tagged the same way. Replace lib/tasks.ts:
Then replace the starter’s home page, app/page.tsx, with a summary:
Open http://localhost:3000/ and you’ll see something like “3 tasks, 1 done.” Both functions are tagged tasks: remember that, it matters in a minute.
5. Fix the stale count
Now try this: on /tasks, add a task. Then go back to /. It still shows the old count. The list page is right and the home page is wrong.
That’s the most common caching bug there is. The actions call revalidatePath("/tasks"), which refreshes what the /tasks page used — and nothing else. The count on the home page is its own cache entry, and it will happily stay old for the next hour. The fix is to say which data changed, not which page: every cache entry tagged tasks, wherever it’s used. Replace app/tasks/actions.ts:
Add another task and go back to /: the count is right straight away. The three ways to refresh a cache, and when to use each:
updateTag("tasks"): throws the entries away now, so the person who just saved sees their change. Server actions only — in a route handler it fails with “updateTag can only be called from within a Server Action”.revalidateTag("tasks", "max"): marks them stale; the next visitor still gets the old copy once while a fresh one is built in the background. Use it in route handlers and webhooks — say, when a CMS tells you content changed.revalidatePath("/tasks"): refreshes one page. Fine when only that page shows the data; otherwise reach for a tag.
6. Add a per-visitor setting
Some things can’t be shared between visitors. Let each person hide their done tasks, remembered in a cookie. First, let getTasks take that choice as an argument — replace lib/tasks.ts (getTaskCounts stays as it was):
Arguments are part of the cache key: getTasks(true) and getTasks(false) are kept as two separate entries, both tagged tasks, so updateTag clears both. Next, an action that flips the cookie — replace app/tasks/actions.ts (the same file, with toggleHideDone added at the end):
And the page reads the cookie, then asks the cache for that visitor’s list — replace app/tasks/page.tsx:
- The cookie is read outside the cached function and passed in. Read it inside
getTasksinstead and/tasksstops loading (“This page couldn’t load”), while the terminal — and in development, the error overlay — says “cookies()can’t be read inside"use cache". Read it outside the cached function and pass what you need as an argument.” A cache shared by everyone can’t depend on one person’s cookie — but it can be given that person’s *choice* as a key. - Reading
cookies()needs a real request, so it sits inside<Suspense>. Runnpm run build:/tasksis◐again — the outline is static, the visitor’s part streams in, and it still comes from the cache./stays○.
Try it: click Hide done tasks and the done ones disappear, with their own “List cached at” time (that’s the second cache entry). Open the page in a private window: that visitor still sees every task. Add a task in either window: both lists and the home page update.
7. Dates, times and random values
cachedAt uses new Date() inside "use cache", which is fine: the time is captured once and stored with the entry — that’s the point. Outside a cache it’s a different story. Put <p>Today is {new Date().toDateString()}</p> in the home page and the build stops with “Next.js encountered the unstable value new Date() while prerendering.” Next.js can’t know whether you meant the time of the build or the time of each visit, so it makes you choose:
- The same value for everyone, refreshed on a schedule: compute it inside a
"use cache"function. - A new value on every visit: call
await connection()first, in a component inside<Suspense>— the pattern from the Prisma guide. - The visitor’s own clock: render it in a
"use client"component. Math.random()andcrypto.randomUUID()follow the same rules.
8. Choosing how long to cache
cacheLife takes one of these profiles (or your own numbers):
"minutes": refreshed in the background after a minute, thrown away after an hour."hours": after an hour; thrown away after a day."days": after a day; after a week."weeks"and"max": for things that hardly ever change."seconds": refreshed every second, gone after a minute. So short-lived that Next.js leaves it out of the build’s HTML: a page using it must put that part inside<Suspense>, or the build stops with “uncached or runtime data during prerendering”.
“Refreshed in the background” means the visitor who arrives after the hour still gets the old copy, instantly, while a new one is made. A good rule: cache with a long life and a tag, and call updateTag when the data changes. Time is only a safety net for changes your code doesn’t know about. Without a cacheLife, Next.js uses its default profile (refreshed after 15 minutes, never thrown away).
9. In production
- Every deploy starts with an empty cache. Entries never carry over from an old deploy, so a deploy can’t serve data your old code cached.
- On a serverless host like Vercel, the runtime cache lives in each server instance’s memory. The parts in the build’s HTML (
○pages, and the static outline of◐ones) are served from the CDN, but an entry made at request time may be made again by another instance. For a cache shared across instances, Next.js has"use cache: remote". - Caching never replaces checks. A cached function shared by everyone must never return one person’s private data: pass in only what decides the result (like
hideDone), never a session or a user’s secrets.
Errors you’ll meet, and what they mean
Each of these was reproduced on purpose while writing this guide:
- “Next.js encountered uncached or runtime data during prerendering.” Something needs a real request (a database read,
cookies(),searchParams) and isn’t inside<Suspense>or a cache. Either cache it with"use cache"or move it into a component inside<Suspense>. - “
cookies()can’t be read inside"use cache". Read it outside the cached function and pass what you need as an argument.” As in step 6: read it outside, pass the value in. The same goes forheaders(). Depending on where the cached function is used, this shows up when you build, or only when the page is opened (“This page couldn’t load”, with the message in the terminal). - “Next.js encountered the unstable value
new Date()while prerendering.” See step 7: cache it, compute it per request withconnection(), or render it on the client. - “To use "use cache", please enable the feature flag
cacheComponentsin your Next.js config.” Step 1. - “
cacheComponentsis enabled without a correspondingpartialPrefetchingoption.” A warning: addpartialPrefetching: true(step 1). - “updateTag can only be called from within a Server Action.” You called it from a route handler (a webhook, say). Use
revalidateTag("tasks", "max")there. - “Attempted to call a temporary Client Reference from the server but it is on the client.” A confusing one: you passed a function into a
"use cache"function. Arguments become the cache key, so they must be plain values — strings, numbers, booleans, arrays, plain objects. Pass the value the function would have computed instead. - No error, but saved changes don’t show up. The action didn’t call
updateTag(orrevalidateTag), or the tag name doesn’t match the one incacheTag. Tags are case-sensitive. - A page with
cacheLife("seconds")fails the build with “uncached or runtime data during prerendering”. Step 8: short-lived caches are left out of the HTML, so that part needs<Suspense>.
Questions people ask
What is Cache Components in Next.js 16?
It’s how Next.js 16 caches, switched on with cacheComponents: true in next.config.ts. Pages are built ahead of time wherever possible, and you mark the slow parts you want kept with "use cache". New create-next-app projects have it on already, which is why a plain database read can suddenly fail the build.
What’s the difference between updateTag and revalidateTag?
updateTag throws the cached data away immediately, so the person who just saved sees their change. It only works in server actions. revalidateTag(tag, "max") marks it stale instead: the next visitor gets the old copy once while a fresh one is built. That’s the one to use in route handlers and webhooks.
Why does my page still show old data after I save?
Usually because you refreshed a page instead of the data. revalidatePath("/tasks") only refreshes what /tasks used, so the same data cached for another page stays old. Tag the cached function with cacheTag, call updateTag with that tag in your action, and every page that uses it updates.
Can I read cookies inside "use cache"?
No. A cache is shared by everyone, so it can’t depend on one visitor’s cookie. Read the cookie outside the cached function and pass what you need in as an argument. Arguments are part of the cache key, so each value gets its own entry.
Where to go next
- Add accounts with Better Auth, then cache each person’s data by passing their user id into the cached function — never their session.
- When a webhook changes data (like the Stripe guide’s orders), call
revalidateTagfrom the route handler. - Read Next.js’s own caching guide for
"use cache: private", prefetching and the static shell in depth.