Thuta Learning
Next.js
IntermediateWeb DevelopmentIntermediate

Cache Components and Revalidation

Next.jsLesson 1535 min

What you'll walk away with

  • Tell a statically rendered route from a dynamic one and name what makes a route dynamic
  • Set time-based revalidation on a fetch and explain stale-while-revalidate
  • Refresh cached data on demand after a mutation with revalidatePath or revalidateTag
  • Keep per-user data out of shared caches
  • Recognise the Next.js 16 Cache Components model ("use cache", cacheLife, cacheTag)

Explain it simply

Caching and revalidation in plain language

A bakery that bakes bread once in the morning and sells it from the shelf all day is fast. A bakery that bakes every loaf to order is fresh but slow. Caching in Next.js is choosing, page by page and piece of data by piece of data, which of those two shops you want to run.

Revalidation is the rule for when the shelf gets restocked. It can be on a timer, such as once an hour (time-based), or the moment the baker says 'this batch changed' (on-demand).

Problem → Why → Solution

The problem: fast, but stale

The /notes page of a notes site calls the CMS for every visitor. As traffic grows, the CMS slows down and starts hitting rate limits, so the developer caches the fetch for a whole day. The page is instantly fast, but when an editor publishes a note, readers do not see it until the next day, because the publish action never tells anyone the cached list is out of date.

app/lib/notes.ts
export async function getPublicNotes() {
  const res = await fetch(CMS_URL, { next: { revalidate: 86400 } }); // 1 day
  return res.json();
}

export async function publishNote(formData: FormData) {
  "use server";
  await saveNoteToCms(formData);
  // nothing marks the cached list as stale, so readers wait up to a day
}

Caching is not a single switch

Every piece of data has its own freshness need. Without a rule for when a cache entry expires and who triggers a refresh, you are stuck choosing between slow and stale. Revalidation gives you both: cached reads that are fast, plus an explicit invalidation the moment you know the data changed.

Core concept: static, dynamic and two kinds of revalidation

When you run next build, Next.js tries to prerender every route. A static route is rendered once at build time into HTML plus an RSC payload and then served from the cache to every visitor. A route becomes dynamic when it needs information that only exists at request time: calling cookies() or headers(), reading searchParams, or using data you opted out of caching. The build output marks each route with a symbol (for example ○ for static and ƒ for dynamic), so you can always check which kind you got.

Time-based revalidation says 'cache this for at most N seconds': fetch(url, { next: { revalidate: 3600 } }), or export const revalidate = 3600 in a page. It works as stale-while-revalidate. The first request after the window expires still gets the old copy immediately while Next.js fetches fresh data in the background, and only the requests after that see the new copy. So revalidate: 60 does not mean 'updates exactly every 60 seconds'.

On-demand revalidation is for when you know the data changed, usually inside a Server Action or a Route Handler. revalidatePath("/notes") marks what is cached for that path as stale. revalidateTag("notes") invalidates every fetch tagged notes, whichever pages use it. When one piece of data appears on many pages, a tag is the more precise tool.

ToolWhat it does
next: { revalidate: N }caches a fetch result for N seconds, then refreshes it in the background
next: { tags: ["x"] }names a fetch result so it can be invalidated later
revalidatePath(path)marks the cache for one path as stale
revalidateTag(tag)invalidates all data with that tag, on any page

The defaults changed between versions

Next.js 14 cached fetch by default, Next.js 15 stopped doing so, and Next.js 16 added the opt-in Cache Components model. Do not rely on a remembered default: state your caching explicitly and check the official caching guide for the version in your package.json.

The cache as a shelf with restock rules
  1. Build: prerender what can be static
  2. Request: serve the cached copy
  3. Window ends: serve stale, refetch
  4. Mutation: revalidatePath or Tag
  5. Next request gets fresh data

Think about freshness per piece of data: pick a time window for each, and call invalidation yourself whenever you know it changed.

General pattern

tsx
// time-based: cache this data for at most N seconds, give it a tag
await fetch(url, { next: { revalidate: seconds, tags: ["tag-name"] } });

// time-based for a whole route segment (page.tsx or layout.tsx)
export const revalidate = seconds;

// on-demand, inside a Server Action or Route Handler
revalidatePath("/some/path");
revalidateTag("tag-name"); // Next.js 16: revalidateTag("tag-name", "max")

Say how stale the data may get with revalidate, and call revalidatePath or revalidateTag wherever you learn about a change. In Next.js 16, revalidateTag takes a cacheLife profile as a second argument; check the reference for your version.

Worked example: cache for an hour, refresh on publish

The two files below fix the problem. getPublicNotes caches the CMS response for up to an hour and tags it notes. publishNote revalidates the /notes path right after saving, so readers no longer wait for the hour to pass. This pattern works in Next.js 14, 15 and 16 (when Cache Components is not enabled).

app/lib/notes.ts
// app/lib/notes.ts
export type Note = { id: string; title: string };

export async function getPublicNotes(): Promise<Note[]> {
  const res = await fetch("https://cms.example.com/api/notes", {
    next: { revalidate: 3600, tags: ["notes"] }, // cache for up to 1 hour
  });
  if (!res.ok) throw new Error(`CMS responded with ${res.status}`);
  return res.json();
}

// app/notes/actions.ts
"use server";
import { revalidatePath } from "next/cache";
import { saveNoteToCms } from "@/lib/cms";

export async function publishNote(formData: FormData) {
  // validate the input and check permissions first (lessons 18 and 20)
  await saveNoteToCms(formData);
  revalidatePath("/notes"); // the next visit to /notes renders fresh data
}

Code breakdown

  1. Time window and tagnext: { revalidate: 3600, tags: ["notes"] }, // cache for up to 1 hour

    revalidate: 3600 lets the response be reused for up to an hour, and tags names it so revalidateTag("notes") can find it later.

  2. Fail loudlyif (!res.ok) throw new Error(`CMS responded with ${res.status}`);

    It checks the status first so an error response is never treated as the notes list; throwing lets the nearest error.tsx handle it.

  3. A server-only mutation"use server";

    This makes publishNote a Server Action; cache functions such as revalidatePath can only be called on the server.

  4. Invalidate after savingrevalidatePath("/notes"); // the next visit to /notes renders fresh data

    It runs only after the save succeeds. If the list also appears on the home page, revalidating the notes tag is better, because it clears that data everywhere at once.

You should see
The first visit after a deploy loads the list from the CMS and caches it for up to an hour. Visits within that hour are served from the cache. After publishNote runs, /notes is marked stale, so the next visit shows the new note.

Stale-while-revalidate on a timeline

text
revalidate: 3600 with four visitors
-----------------------------------
time      0 min      10 min       61 min            62 min
           |          |            |                 |
visitor    A          B            C                 D
cache      MISS       HIT          STALE             HIT
           fetch and  serve the    serve old copy,   serve the
           store      cached copy  refetch in bg     new copy

C arrives after the hour is up but still gets the old copy; their request is what triggers the refresh. Only D sees the new data. If nobody visits, nothing refreshes, which is why 'show it right after publishing' is solved with on-demand revalidation rather than a shorter timer.

The Next.js 16 Cache Components model

Next.js 16 has an opt-in model you enable with cacheComponents: true in next.config.ts. Instead of setting options for a whole page, you put the "use cache" directive inside the function or component you want cached, give it a lifetime with cacheLife and a tag with cacheTag. With this mode on, cacheLife takes the place of older route segment options such as export const revalidate.

app/lib/notes.ts (Next.js 16, cacheComponents: true)
import { cacheLife, cacheTag } from "next/cache";
import { db } from "@/lib/db";

export async function getPublicNotes() {
  "use cache";
  cacheLife("hours");
  cacheTag("notes");
  return db.note.findMany({ where: { published: true } });
}

// in a Server Action after a change: updateTag("notes");

The arguments of a "use cache" function become part of its cache key, but the function cannot read request data such as cookies() directly; read it outside and pass it in. Next.js 16 also added updateTag, used inside a Server Action so the user sees their own change immediately, while revalidateTag(tag, "max") refreshes in the stale-while-revalidate style. These APIs are new, so check the official docs before relying on them.

In real projects

How real projects use it

Most sites mix two kinds of data: data everyone sees the same way that rarely changes, and data that differs per request. Caching the first and keeping the second dynamic is both fast and safe.

  • Blogs and docs sites revalidate article pages hourly or daily, and a Route Handler that verifies a secret calls revalidateTag when the CMS sends a webhook.
  • Online shops cache product descriptions and images for a long time but read stock levels and the cart dynamically on every request.
  • Dashboards keep each user's records dynamic, out of any shared cache, and cache only shared data such as a public exchange rate shown in a chart.

Teams usually set the window in business terms: 'a price change may take five minutes to appear' becomes revalidate: 300, while 'it must show immediately' calls for on-demand invalidation.

Common mistakes

Common caching mistakes

Putting per-user data in a shared cache

If the cache key does not include who is asking, everyone may receive the first visitor's result: a privacy incident where people see someone else's orders or email. Keep personal data dynamic, or make the user part of the key and never share it through a public cache.

Mutating without invalidating

Updating the database without calling revalidatePath or revalidateTag leaves the old copy on screen until its window expires. For every save, update or delete action, ask which caches it affects.

Invalidating the wrong path or tag

If the list appears on both /notes and / but you only call revalidatePath("/notes"), the home page stays stale. A misspelled tag string fails silently too, so declare tags as constants in one place.

Expecting revalidate: 60 to update on the dot

The first request after the window still receives the old copy. If a change must appear immediately, use on-demand revalidation rather than shrinking the timer.

Best practices

Best practices

  • Write revalidate or cacheLife explicitly on data you want cached instead of guessing the default.
  • Tag data that several pages share and prefer revalidateTag for it.
  • Read the next build output to confirm that routes you expect to be static really are.
  • Treat anything that depends on cookies, the session or a user id as dynamic by default.

Mini challenge

Mini challenge: simulate the cache in TypeScript

Model Next.js's two revalidation rules in plain TypeScript: an expired entry serves its old copy once while it refreshes (stale-while-revalidate), and tag-based invalidation expires entries immediately. A fake clock keeps the output deterministic.

  • get() returns MISS when there is no entry, HIT inside the window, and STALE (the old value) after it
  • On STALE, store the newly loaded value for the next read
  • revalidateTag(tag) removes entries carrying that tag so the next read is a MISS
  • Print the status and value of every read
tiny-cache.ts
type Status = "MISS" | "HIT" | "STALE";
type Options = { revalidateSec: number; tags: string[] };

class TinyCache {
  // TODO: store value, storedAt and tags per key

  constructor(private now: () => number) {}

  get<T>(key: string, load: () => T, opts: Options): { value: T; status: Status } {
    // TODO: no entry -> load, store, MISS
    // TODO: older than revalidateSec -> return the OLD value as STALE,
    //       but store a freshly loaded one for the next read
    // TODO: otherwise -> HIT
  }

  revalidateTag(tag: string): void {
    // TODO: delete every entry whose tags include `tag`
  }
}

// TODO: drive it with a fake clock and a "version" counter for the data

Expected: Reads print MISS v1, HIT v1, STALE v1, HIT v2; after revalidateTag the next read is MISS v3 and the one after it HIT v3.

Show hint

Compute an entry's age as (now() - storedAt) / 1000. To simulate the background refresh, keep the old value in a variable before storing the new one.

Show solution
tiny-cache.ts
type Status = "MISS" | "HIT" | "STALE";
type Options = { revalidateSec: number; tags: string[] };
type Entry = { value: unknown; storedAt: number; tags: string[] };

class TinyCache {
  private entries = new Map<string, Entry>();

  constructor(private now: () => number) {}

  get<T>(key: string, load: () => T, opts: Options): { value: T; status: Status } {
    const store = (): T => {
      const value = load();
      this.entries.set(key, { value, storedAt: this.now(), tags: opts.tags });
      return value;
    };
    const entry = this.entries.get(key);
    if (!entry) return { value: store(), status: "MISS" };

    const ageSec = (this.now() - entry.storedAt) / 1000;
    if (ageSec > opts.revalidateSec) {
      const old = entry.value as T;
      store(); // stands in for the background refresh
      return { value: old, status: "STALE" };
    }
    return { value: entry.value as T, status: "HIT" };
  }

  revalidateTag(tag: string): void {
    for (const [key, entry] of this.entries) {
      if (entry.tags.includes(tag)) this.entries.delete(key);
    }
  }
}

let clock = 0;
let version = 1;
const cache = new TinyCache(() => clock);
const opts = { revalidateSec: 3600, tags: ["notes"] };

function read(label: string) {
  const { value, status } = cache.get("notes-list", () => `notes v${version}`, opts);
  console.log(`${label.padEnd(15)} ${status.padEnd(5)} ${value}`);
}

read("t=0");
clock = 10 * 60_000;
read("t=10min");
version = 2;
clock = 61 * 60_000;
read("t=61min");
read("t=61min again");
version = 3;
cache.revalidateTag("notes"); // what a publish action would trigger
read("after publish");
read("next visit");

Quick quiz 1 / 3

A fetch uses next: { revalidate: 60 } and its data was cached at 12:00:00. A request arrives at 12:01:30. What does that visitor see?

Quick quiz 2 / 3

Which of these makes a route render dynamically at request time?

Quick quiz 3 / 3

The notes list appears on both /notes and the home page /, and its fetch has tags: ["notes"]. After publishing, which call refreshes both places?

What to remember

  • Static routes render at build time; request data such as cookies(), headers() and searchParams makes a route dynamic.
  • next: { revalidate: N } is stale-while-revalidate: the first request after the window gets the old copy and triggers a refresh.
  • Call revalidatePath or revalidateTag when you know data changed; tags are more precise for data shared by many pages.
  • Keep personal data out of shared caches, and check the docs because caching defaults differ across Next.js 14, 15 and 16.

Next.js — Revalidating — Next.js

Next.js — Revalidating — Next.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Cache Components and Revalidation | Thuta Learning