PERFORMANCENEXT.JS 16CACHING

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.

Ali Murtaza · 16 min read ·

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 /tasks page 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 dev running 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:

next.config.ts (add inside nextConfig, if missing)ts
cacheComponents: true, partialPrefetching: true,
  • cacheComponents turns 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 flag cacheComponents in your Next.js config.”
  • partialPrefetching makes links prefetch the parts of a page that can be prepared ahead of time. Set it explicitly: with only cacheComponents, every build warns “cacheComponents is enabled without a corresponding partialPrefetching option.”

Restart npm run dev after changing next.config.ts.

2. Read what the build tells you

Terminalbash
npm run build

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:

lib/tasks.tsts
import { cacheLife, cacheTag } from "next/cache";import { prisma } from "@/lib/prisma";export async function getTasks() { "use cache"; cacheLife("hours"); cacheTag("tasks"); const tasks = await prisma.task.findMany({ orderBy: { createdAt: "asc" } }); return { tasks, cachedAt: new Date().toLocaleTimeString("en-GB") };}
  • "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).
  • cachedAt is 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():

app/tasks/page.tsxtsx
import { Suspense } from "react";import { getTasks } from "@/lib/tasks";import { AddTaskForm } from "./add-task-form";import { deleteTask, toggleTask } from "./actions";export default function TasksPage() { return ( <main className="mx-auto max-w-xl p-8"> <h1 className="text-2xl font-semibold">Tasks</h1> <AddTaskForm /> <Suspense fallback={<p className="mt-6">Loading tasks…</p>}> <TaskList /> </Suspense> </main> );}async function TaskList() { const { tasks, cachedAt } = await getTasks(); if (tasks.length === 0) { return <p className="mt-6 text-sm">No tasks yet. Add your first one above.</p>; } return ( <> <ul className="mt-6 divide-y rounded border"> {tasks.map((task) => ( <li key={task.id} className="flex items-center gap-3 px-3 py-2"> <form action={toggleTask}> <input type="hidden" name="id" value={task.id} /> <button type="submit" aria-label={task.done ? "Mark as not done" : "Mark as done"}> {task.done ? "☑" : "☐"} </button> </form> <span className={task.done ? "flex-1 line-through opacity-60" : "flex-1"}> {task.title} </span> <form action={deleteTask}> <input type="hidden" name="id" value={task.id} /> <button type="submit" className="text-sm text-red-600"> Delete </button> </form> </li> ))} </ul> <p className="mt-2 text-xs opacity-60">List cached at {cachedAt}</p> </> );}
Terminalbash
npm run build

/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:

lib/tasks.tsts
import { cacheLife, cacheTag } from "next/cache";import { prisma } from "@/lib/prisma";export async function getTasks() { "use cache"; cacheLife("hours"); cacheTag("tasks"); const tasks = await prisma.task.findMany({ orderBy: { createdAt: "asc" } }); return { tasks, cachedAt: new Date().toLocaleTimeString("en-GB") };}export async function getTaskCounts() { "use cache"; cacheLife("hours"); cacheTag("tasks"); const [total, done] = await Promise.all([ prisma.task.count(), prisma.task.count({ where: { done: true } }), ]); return { total, done };}

Then replace the starter’s home page, app/page.tsx, with a summary:

app/page.tsxtsx
import Link from "next/link";import { getTaskCounts } from "@/lib/tasks";export default async function Home() { const { total, done } = await getTaskCounts(); return ( <main className="mx-auto max-w-xl p-8"> <h1 className="text-2xl font-semibold">My tasks</h1> <p className="mt-2"> {total} tasks, {done} done. </p> <Link href="/tasks" className="mt-4 inline-block underline"> Open the list </Link> </main> );}

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:

app/tasks/actions.tsts
"use server";import { updateTag } from "next/cache";import { prisma } from "@/lib/prisma";export type FormState = { error: string } | null;export async function addTask( _previous: FormState, formData: FormData,): Promise<FormState> { const title = String(formData.get("title") ?? "").trim(); if (!title) return { error: "Write a task first." }; if (title.length > 200) return { error: "Keep it under 200 characters." }; await prisma.task.create({ data: { title } }); updateTag("tasks"); return null;}export async function toggleTask(formData: FormData) { const id = Number(formData.get("id")); const task = await prisma.task.findUnique({ where: { id } }); if (!task) return; await prisma.task.update({ where: { id }, data: { done: !task.done } }); updateTag("tasks");}export async function deleteTask(formData: FormData) { const id = Number(formData.get("id")); await prisma.task.deleteMany({ where: { id } }); updateTag("tasks");}

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):

lib/tasks.tsts
import { cacheLife, cacheTag } from "next/cache";import { prisma } from "@/lib/prisma";export async function getTasks(hideDone = false) { "use cache"; cacheLife("hours"); cacheTag("tasks"); const tasks = await prisma.task.findMany({ where: hideDone ? { done: false } : undefined, orderBy: { createdAt: "asc" }, }); return { tasks, cachedAt: new Date().toLocaleTimeString("en-GB") };}export async function getTaskCounts() { "use cache"; cacheLife("hours"); cacheTag("tasks"); const [total, done] = await Promise.all([ prisma.task.count(), prisma.task.count({ where: { done: true } }), ]); return { total, done };}

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):

app/tasks/actions.tsts
"use server";import { cookies } from "next/headers";import { updateTag } from "next/cache";import { prisma } from "@/lib/prisma";export type FormState = { error: string } | null;export async function addTask( _previous: FormState, formData: FormData,): Promise<FormState> { const title = String(formData.get("title") ?? "").trim(); if (!title) return { error: "Write a task first." }; if (title.length > 200) return { error: "Keep it under 200 characters." }; await prisma.task.create({ data: { title } }); updateTag("tasks"); return null;}export async function toggleTask(formData: FormData) { const id = Number(formData.get("id")); const task = await prisma.task.findUnique({ where: { id } }); if (!task) return; await prisma.task.update({ where: { id }, data: { done: !task.done } }); updateTag("tasks");}export async function deleteTask(formData: FormData) { const id = Number(formData.get("id")); await prisma.task.deleteMany({ where: { id } }); updateTag("tasks");}export async function toggleHideDone() { const cookieStore = await cookies(); const hidden = cookieStore.get("hideDone")?.value === "1"; cookieStore.set("hideDone", hidden ? "0" : "1", { path: "/", maxAge: 60 * 60 * 24 * 365, });}

And the page reads the cookie, then asks the cache for that visitor’s list — replace app/tasks/page.tsx:

app/tasks/page.tsxtsx
import { Suspense } from "react";import { cookies } from "next/headers";import { getTasks } from "@/lib/tasks";import { AddTaskForm } from "./add-task-form";import { deleteTask, toggleHideDone, toggleTask } from "./actions";export default function TasksPage() { return ( <main className="mx-auto max-w-xl p-8"> <h1 className="text-2xl font-semibold">Tasks</h1> <AddTaskForm /> <Suspense fallback={<p className="mt-6">Loading tasks…</p>}> <VisitorTasks /> </Suspense> </main> );}/** Reads this visitor's preference, then asks the cache for that list. */async function VisitorTasks() { const hideDone = (await cookies()).get("hideDone")?.value === "1"; return <TaskList hideDone={hideDone} />;}async function TaskList({ hideDone }: { hideDone: boolean }) { const { tasks, cachedAt } = await getTasks(hideDone); return ( <> <form action={toggleHideDone} className="mt-6"> <button type="submit" className="text-sm underline"> {hideDone ? "Show done tasks" : "Hide done tasks"} </button> </form> {tasks.length === 0 ? ( <p className="mt-4 text-sm">No tasks to show.</p> ) : ( <ul className="mt-4 divide-y rounded border"> {tasks.map((task) => ( <li key={task.id} className="flex items-center gap-3 px-3 py-2"> <form action={toggleTask}> <input type="hidden" name="id" value={task.id} /> <button type="submit" aria-label={task.done ? "Mark as not done" : "Mark as done"}> {task.done ? "☑" : "☐"} </button> </form> <span className={task.done ? "flex-1 line-through opacity-60" : "flex-1"}> {task.title} </span> <form action={deleteTask}> <input type="hidden" name="id" value={task.id} /> <button type="submit" className="text-sm text-red-600"> Delete </button> </form> </li> ))} </ul> )} <p className="mt-2 text-xs opacity-60">List cached at {cachedAt}</p> </> );}
  • The cookie is read outside the cached function and passed in. Read it inside getTasks instead and /tasks stops 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>. Run npm run build: /tasks is ◐ 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() and crypto.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 for headers(). 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 with connection(), or render it on the client.
  • “To use "use cache", please enable the feature flag cacheComponents in your Next.js config.” Step 1.
  • “cacheComponents is enabled without a corresponding partialPrefetching option.” A warning: add partialPrefetching: 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 (or revalidateTag), or the tag name doesn’t match the one in cacheTag. 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 revalidateTag from the route handler.
  • Read Next.js’s own caching guide for "use cache: private", prefetching and the static shell in depth.
Found this useful? Give it a heart, or share it with someone who’d use it.
WRITTEN BY
Ali Murtaza

I build SaaS products with Next.js and teach them start to finish, in full courses here and free builds on YouTube.

KEEP READING
FREE BUILDS ON THIS STACK