Skip to content

No. 48Next.js8 min read2,188 words

Next.js caching explained: use cache, tags and revalidation

Next.js caching explained for Next.js 16: use cache, cacheLife, cacheTag, updateTag vs revalidateTag, the client router cache, and how to debug stale data.

Written by
Lazy Devs
Published
Updated
Sources
Cited inline

Key takeaways ยท 05

The short version

  1. 01Since Next.js 15, fetch requests are not cached by default, and in Next.js 16 caching is something you opt into deliberately, either with the 'use cache' directive (Cache Components) or with fetch and route segment options (the previous model).
  2. 02With Cache Components, mark data or components with 'use cache', set a lifetime with cacheLife, label entries with cacheTag, and invalidate the tag when the underlying data changes.
  3. 03Use updateTag in a Server Action when the user must see their own change immediately; use revalidateTag(tag, 'max') for stale-while-revalidate updates, including from webhooks and Route Handlers.
  4. 04React cache() deduplicates a database call within one request; it is not a cross-request cache. 'use cache' and the fetch cache persist across requests and users.
  5. 05Never cache user-specific data under a shared key. Read cookies outside the cached function and pass the user or tenant ID in as an argument so it becomes part of the cache key.
On this page ยท 12

Next.js caching stops being confusing once you know two things: which caching model your app is on, and what has to happen when data changes. In Next.js 16, caching is opt-in. You mark data or components as cacheable with "use cache" (or with fetch options if you are not using Cache Components), give the entry a lifetime and a tag, and invalidate that tag in the code that writes the data. Everything else is detail on where each cache lives.

Most "Next.js caching is broken" complaints we hear are really version mismatches. The defaults changed in Next.js 15 and the model changed again in 16, so advice that was right two years ago now produces bugs. This guide is the explanation we wish we had been handed before we shipped a page that served hours-old data and blamed the backend.

First: which caching model are you on?

Before reasoning about any caching behaviour, check your Next.js version and whether cacheComponents is enabled in next.config.ts.

Version and configfetch cached by default?How you cacheHow you invalidate
Next.js 14 and earlierYes, indefinitelyOpt out with cache: "no-store"revalidateTag(tag), revalidatePath
Next.js 15Nocache: "force-cache", next.revalidate, unstable_cacherevalidateTag(tag), revalidatePath
Next.js 16 without Cache ComponentsNoSame as 15revalidateTag(tag, "max"), updateTag, revalidatePath
Next.js 16 with cacheComponents: trueNo; everything is dynamic unless cached"use cache", cacheLife, cacheTagupdateTag, revalidateTag(tag, "max"), revalidatePath

New projects should start with Cache Components. It is where the framework is heading, it enables Partial Prerendering, and it makes caching explicit in the code rather than implied by which APIs a route happens to call. Existing apps can stay on the previous model, which is still documented and supported.

The layers, from request to browser

Whichever model you use, there are several layers between your database and the user's screen. They stack rather than compete.

LayerWhere it livesHow longWhat it is for
Request memoization (fetch dedupe, React cache)Server, one requestA single renderAvoid running the same query twice per request
Data and component cache ("use cache", cached fetch)ServerUntil it expires or is invalidatedAvoid repeating expensive work across requests and users
Prerendered output (static routes, static shell)Server or CDNUntil revalidated or redeployedServe HTML without rendering at request time
Client router cacheBrowser memorySeconds to minutesInstant back/forward and repeat navigations
HTTP and CDN cacheCDN, browserPer Cache-ControlServe responses without reaching your server

The two that surprise people in production are the server data cache, because it is shared across users, and the client router cache, because it makes a page look as if it "did not update".

Request memoization: dedupe within one render

If you call the same fetch several times while rendering one page, Next.js runs the request once and shares the result. For database queries and other non-fetch work, wrap the function in React's cache:

import { cache } from "react";
import { db } from "@/lib/db";
 
export const getUser = cache(async (id: string) => {
  return db.user.findUnique({ where: { id } });
});

Now getUser("42") called from a layout, a page and three components hits the database once per request. That is all it does. It does not persist between requests, so it is safe for user-specific data and does nothing for load across requests. It is the foundation of the patterns in data fetching in React Server Components.

Caching with Cache Components: "use cache"

With cacheComponents: true, nothing is cached until you say so. The "use cache" directive caches the return value of an async function or component. Put it at the top of a data function or a component body:

// lib/products.ts
import { cacheLife, cacheTag } from "next/cache";
import { db } from "@/lib/db";
 
export async function getProduct(id: string) {
  "use cache";
  cacheLife("hours");
  cacheTag(`product-${id}`, "products");
 
  return db.product.findUnique({ where: { id } });
}

Three things are happening:

  1. The cache key is built from the build ID, the function's identity and its serializable arguments, plus any variables it closes over. getProduct("1") and getProduct("2") are separate entries.
  2. cacheLife sets how long the entry stays fresh.
  3. cacheTag labels the entry so you can invalidate it on demand.

Choosing a lifetime with cacheLife

cacheLife takes a preset profile or a custom one. Each profile sets three values: stale (how long the browser can reuse the result without asking the server), revalidate (after which the server serves the cached copy and refreshes it in the background) and expire (after which, with no traffic, the next request waits for fresh data).

ProfileGood forstalerevalidateexpire
secondsNear real-time data30 seconds1 second1 minute
minutesFrequently updated content5 minutes1 minute1 hour
hoursContent updated a few times a day5 minutes1 hour1 day
daysContent updated daily5 minutes1 day1 week
weeksContent updated weekly5 minutes1 week30 days
maxContent that rarely changes5 minutes30 days1 year

If you do not call cacheLife, the default profile applies (revalidate every 15 minutes, never expire). We recommend always setting a profile explicitly, so the next person reading the code knows what you intended.

What cannot go inside a cached function

Cached functions cannot call cookies(), headers() or read searchParams directly. That is a feature: it stops you caching one user's data and serving it to everyone. Read request data outside, then pass what you need as an argument:

import { cookies } from "next/headers";
import { cacheLife, cacheTag } from "next/cache";
 
async function Dashboard() {
  const tenantId = (await cookies()).get("tenant")?.value ?? "public";
  return <TenantStats tenantId={tenantId} />; // tenantId is part of the cache key
}
 
async function TenantStats({ tenantId }: { tenantId: string }) {
  "use cache";
  cacheLife("minutes");
  cacheTag(`tenant-${tenantId}`);
  const stats = await getStats(tenantId);
  return <StatsGrid stats={stats} />;
}

Where the cache actually lives

By default, runtime cache entries are kept in memory. On a long-running self-hosted server they persist across requests. On serverless platforms, each request can land on a different instance, so runtime entries often do not survive; build-time prerendering works normally either way. The docs suggest "use cache: remote" when you need a durable cache shared across instances, backed by a cache handler such as Redis or a KV store. If you are deciding whether that layer is worth it, our practical guide to Redis caching covers the trade-offs.

Invalidation: tell Next.js what changed

Caching reads is the easy half. The rule that keeps data fresh: every write must announce what it changed, by tag or by path, in the same code that performed the write.

APIWhere you can call itWhat it doesUse it for
updateTag(tag)Server Actions onlyExpires the tag immediately; the next read waits for fresh data instead of serving staleForms and settings where the user expects to see their own change
revalidateTag(tag, "max")Server Actions, Route HandlersMarks the tag stale; next visit serves stale content while refreshingCMS webhooks, catalog updates, anything where a brief delay is fine
revalidatePath(path)Server Actions, Route HandlersInvalidates a specific page or layout pathWhen you know the route, not the data
refresh()Server ActionsRefreshes the client router without touching cached dataUpdating uncached UI like a notification count

updateTag gives read-your-own-writes semantics:

"use server";
 
import { updateTag } from "next/cache";
import { requireUser } from "@/lib/session";
import { db } from "@/lib/db";
 
export async function renameProduct(id: string, name: string) {
  const user = await requireUser();
  if (user.role !== "admin") throw new Error("FORBIDDEN"); // authorize, not just authenticate
  await db.product.update({ where: { id }, data: { name } });
  updateTag(`product-${id}`); // the next render sees the new name
}

revalidateTag is the right tool for a webhook from your CMS or payment provider:

// app/api/cms-webhook/route.ts
import { revalidateTag } from "next/cache";
 
export async function POST(req: Request) {
  if (req.headers.get("x-webhook-secret") !== process.env.CMS_WEBHOOK_SECRET) {
    return new Response("Unauthorized", { status: 401 });
  }
  revalidateTag("products", "max");
  return Response.json({ revalidated: true });
}

In Next.js 16, the single-argument revalidateTag(tag) is deprecated and produces a TypeScript error. Pass a profile ("max" is the recommended one) or switch to updateTag inside Server Actions. If your webhook endpoint takes outside traffic, verify its signature properly; our guide to webhooks done right covers how.

The previous model: fetch options and segment config

If you are not using Cache Components, caching is controlled per fetch and per route:

// Cache until invalidated
fetch(url, { cache: "force-cache", next: { tags: ["prices"] } });
 
// Time-based: refresh at most every 60 seconds
fetch(url, { next: { revalidate: 60 } });
 
// Never cache (the default since Next.js 15)
fetch(url, { cache: "no-store" });

For database queries, unstable_cache plays the role "use cache" plays in the new model. Routes without request-time inputs are prerendered at build time (what older docs call the Full Route Cache), and reading cookies, headers or search params makes a route render per request. Route segment config such as export const revalidate = 3600 or export const dynamic = "force-dynamic" overrides that per route.

The habit is the same as with Cache Components: tag what you cache, invalidate the tag on write.

The client router cache

After you navigate, Next.js keeps rendered route payloads in browser memory so back and forward navigation is instant. This is the cache behind most "I saved it but the page did not change" reports.

The defaults are more conservative than they used to be. Since Next.js 15, dynamically rendered pages are not reused from the client cache by default (staleTimes.dynamic is 0), while static and fully prefetched pages are reused for 5 minutes. Under Cache Components, the stale value from cacheLife controls this per cached entry.

The fix for stale UI is almost never client-side trickery. Invalidate from the server inside the Server Action that did the write, with updateTag, revalidateTag or revalidatePath. When the action returns, the router knows the affected data is stale and refetches it. If you mutate data and the UI does not move, the question is not "why is React not re-rendering", it is "did I tell Next.js what changed?".

HTTP and CDN caching

Underneath all of this, responses still travel through ordinary HTTP caches. Next.js sets Cache-Control headers for prerendered pages so CDNs can serve them, typically using stale-while-revalidate, the directive defined in RFC 5861 that lets a cache serve a stale response while it fetches a fresh one. For Route Handlers and custom responses, set headers deliberately; the MDN Cache-Control reference is the clearest explanation of each directive. Never send public caching headers on responses that contain user-specific data.

How much of this your platform handles for you varies by host; our best hosting for Next.js roundup compares them.

Debugging stale data: a checklist

When a page shows old data, work through these in order:

  1. Confirm the version and model. Check next in package.json and whether cacheComponents is on. A surprising share of the caching bugs we are called in for turn out to be version-mismatch surprises.
  2. Find the cache that holds it. Is the data from a "use cache" function, a cached fetch, a prerendered route or the browser?
  3. Check the write path. Does the code that changes this data call updateTag, revalidateTag or revalidatePath with the right tag or path?
  4. Check the tags match. A typo between cacheTag("product") and updateTag("products") fails silently.
  5. Turn on verbose logging. Running with NEXT_PRIVATE_DEBUG_CACHE=1 logs cache hits, misses and revalidations.
  6. Check the CDN. If the HTML itself is stale, look at the response's Cache-Control and your CDN's cache status headers.

Common mistakes

  • Caching user data under a shared key, so one user's dashboard is served to another. Always pass the user or tenant ID into the cached function.
  • Caching without tagging, so the only way to refresh is waiting for the lifetime to run out.
  • Invalidating in the wrong place, for example in a client callback rather than the Server Action that wrote the data.
  • Assuming in-memory caches persist on serverless platforms.
  • Using force-dynamic to fix one slow query, when caching that query and leaving the rest of the page static would be faster.
  • Copying advice written for Next.js 14, where fetch was cached by default.

A mental model you can keep in your head

Reads are uncached until you choose otherwise. Writes must announce what they changed. In practice:

  • Dedupe within a request with React cache.
  • Cache across requests with "use cache" (or fetch options), an explicit cacheLife and a cacheTag.
  • Invalidate in the Server Action or webhook that wrote the data: updateTag for read-your-own-writes, revalidateTag(tag, "max") for everything else.

Caching decides how often your code runs; rendering decides where and when. The two are easiest to reason about together, which is why we pair this guide with our mental model for App Router rendering. The shell-plus-streaming approach also changes where your code should run.

If your Next.js app is serving data older than it should, or you want caching designed properly from the start, that is everyday work in our Next.js development practice. Tell us what you are seeing.

FAQ ยท 05 questions

Frequently asked questions

Does Next.js cache fetch requests by default?

Not any more. Since Next.js 15, fetch requests are not cached unless you opt in with cache set to force-cache, a revalidate time, or by calling them inside a 'use cache' function. Next.js 14 and earlier cached fetch results by default, which is why older tutorials describe the opposite behaviour.

What is the difference between updateTag and revalidateTag in Next.js 16?

updateTag can only be called from a Server Action and expires the tagged data immediately, so the user who made a change sees it on the very next render. revalidateTag marks the data as stale and, with the recommended 'max' profile, serves the old version while fresh data is fetched in the background. It also works in Route Handlers, which makes it the right choice for webhooks.

Why does my Next.js page show old data after I update the database?

Something cached the old result and nothing told it the data changed. Check which cache holds it: a 'use cache' function or tagged fetch that needs updateTag or revalidateTag after the write, a prerendered route that needs revalidatePath, or the browser's client router cache, which the same server-side invalidation clears. Also confirm which Next.js version and caching model you are on, because defaults changed between 14, 15 and 16.

Does 'use cache' work on serverless platforms?

Yes for build-time prerendering, which works everywhere. Runtime cache entries are stored in memory by default, and on serverless platforms each request may hit a different instance, so those entries often do not persist. For a durable cache shared across instances, the Next.js docs point to 'use cache: remote' with a platform cache handler.

What does React cache() do in Next.js?

React cache() memoizes a function for the duration of a single server request, so calling the same database query from a layout, a page and several components runs it once. It does not store anything between requests or users, so it is safe for user-specific data but does nothing for load across requests.

Related service

Next.js Development Services

Production Next.js apps and sites, tuned for speed and search.

Learn more

Next step

Want this built right?

This is the work we do every day. Tell us what you are building and we will show you exactly how we would ship it.

First reply
Within 1 business day
Typical start
1โ€“2 weeks
Pricing
Fixed price per phase
You own
All code and accounts