Skip to the content

Lesson 179 of 296

Caching and revalidation

What you will learn

  • Why caching matters and what can be cached
  • The Next.js 16 caching model: Cache Components and "use cache"
  • cacheLife and cacheTag
  • revalidateTag, updateTag, revalidatePath and refresh
  • The older caching model you will see in existing code
  • The client-side router cache
On this page

Why cache?

Without caching, every visitor makes the server query the database and render the page again. Caching saves the result and reuses it, making pages faster and reducing load. The hard part is invalidation: making sure users do not see old data after it changes.

Caching in Next.js has changed between versions, and interviewers know it confuses people. Explain the model clearly and mention that it changed.

The big change

  • Next.js 13 and 14: many things were cached automatically (fetch responses, rendered pages). Fast, but surprising: developers saw stale data and did not know why.
  • Next.js 15: fetch requests and GET route handlers were no longer cached by default.
  • Next.js 16: introduced Cache Components, where caching is explicit and opt-in with the "use cache" directive. Dynamic code runs at request time unless you say otherwise.

Enable it in next.config.ts:

TypeScript
const nextConfig = {
  cacheComponents: true
};

export default nextConfig;

"use cache"

Put "use cache" at the top of an async function, a component or a whole page file to cache its result. Next.js builds the cache key automatically from the function's arguments (and anything it closes over).

TSX
import { cacheLife, cacheTag } from "next/cache";

type Course = { slug: string; title: string; lessons: number };

declare function queryCourses(): Promise<Course[]>;

export async function getCourses(): Promise<Course[]> {
  "use cache";
  cacheLife("hours");
  cacheTag("courses");
  return queryCourses();
}
  • cacheLife("hours") sets how long the cached value stays fresh. Built-in profiles include "seconds", "minutes", "hours", "days", "weeks" and "max"; you can also define your own in the config.
  • cacheTag("courses") gives the entry a label, so you can invalidate it later when the data changes.
  • A cached function cannot read request-specific data like cookies() or headers() inside it (the cached result is shared between users). Read those outside and pass the values in as arguments.

Invalidating: four functions

After data changes (usually in a server action, Lesson 181), tell Next.js which cached data is now out of date:

FunctionWhat it doesTypical use
updateTag(tag)Expires the tag and makes the same request see fresh data (read-your-writes). Server actions only.The user saves their profile and must immediately see the change
revalidateTag(tag, profile)Marks tagged entries stale; the next visitor gets the old version while fresh data loads in the background (stale-while-revalidate). In Next.js 16 it takes a cacheLife profile as the second argument, such as "max".A CMS editor publishes an article; slight delay is fine
revalidatePath(path)Invalidates everything cached for a URLSimple cases: "refresh the /blog page"
refresh()Re-renders uncached data on the page without touching the cache. Server actions only.Updating a notification count after marking one as read
TSX
"use server";

import { updateTag } from "next/cache";

declare function saveCourse(slug: string, title: string): Promise<void>;

export async function renameCourse(slug: string, title: string): Promise<void> {
  await saveCourse(slug, title);
  updateTag("courses");
}

Partial pre-rendering (PPR)

With Cache Components, one page can mix static and dynamic parts. Next.js pre-renders a static shell (layout, navigation, cached content) at build time and serves it instantly, while dynamic parts (the user's basket, personalised recommendations) are wrapped in <Suspense> and stream in per request (Lesson 180). This is called Partial Pre-rendering: the fast first load of a static page plus the freshness of a dynamic one.

The older model (you will see it in existing code)

Many current projects use Next.js 14 or 15, or Next.js 16 without Cache Components. Recognise these:

CodeMeaning
fetch(url, { cache: "force-cache" })Cache this response
fetch(url, { next: { revalidate: 60 } })Cache, and refresh at most every 60 seconds
fetch(url, { next: { tags: ["products"] } })Tag the response for revalidateTag
export const revalidate = 3600 in a pageRe-generate the page at most every hour (ISR, Lesson 183)
export const dynamic = "force-dynamic"Always render per request
unstable_cache(fn, keys, options)Cache a non-fetch function (replaced by "use cache")

The layers of caching

LayerWhereWhat
Request memoisationServer, one requestcache() and duplicate fetches run once per render (Lesson 178)
Data cache / "use cache"Server, across requests and usersCached function results and fetch responses
Full route cacheServerThe pre-rendered HTML and RSC payload of static routes
Router cacheBrowserVisited and prefetched route segments, for instant back and forward navigation

The router cache is why a user may see slightly old data when navigating back. router.refresh() (client) or the invalidation functions in a server action clear it.

CDN and HTTP caching

In front of the server, a CDN can cache responses close to users using Cache-Control headers (Part 15). Next.js sets suitable headers for static pages automatically.

How to say it in an interview

"Next.js caching changed a lot: 13 and 14 cached aggressively by default, 15 stopped caching fetch by default, and 16 introduced Cache Components, where caching is opt-in with the 'use cache' directive on functions, components or pages, cacheLife for duration and cacheTag for labels. After a mutation in a server action I call updateTag for read-your-writes, revalidateTag with a profile for stale-while-revalidate, or revalidatePath for a URL. Partial pre-rendering serves a static shell instantly and streams dynamic parts in Suspense. I also know the older fetch revalidate options and the browser's router cache."

Key words

WordMeaning
CacheStored results reused instead of recalculated
InvalidationMarking cached data as out of date
Cache ComponentsNext.js 16 opt-in caching model with "use cache"
cacheLifeHow long a cached value stays fresh
cacheTagA label used to invalidate cached entries
Stale-while-revalidateServe old data while fetching fresh data in the background
Read-your-writesAfter you change data, you see your change immediately
Partial pre-renderingA static shell with dynamic parts streamed in
Router cacheThe browser-side cache of visited route segments

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.