IHOR.DEVKNOWLEDGE_BASE
MENU

~/blog / Web Stack / next-js-caching-and-revalidation-explained.md

// pillar guide · 4 min read

Next.js Caching and Revalidation Explained

Understand Next.js cache scopes, explicit public fetch caching, tag and path invalidation, stale-while-revalidate, and read-your-writes in version 16.

Quick answer

Choose a freshness contract before choosing an invalidation API. Public content that tolerates a briefly stale response can use stale-while-revalidate. A user who has just saved a record may need read-your-writes behavior. Personalized data also needs the correct user and tenant scope. Cache policy is therefore a correctness decision: a fast response containing another customer’s information is a failure, regardless of its latency.

This guide’s fetch example targets Next.js 16 with Cache Components disabled, matching this repository. Current documentation also describes the opt-in Cache Components model with use cache, cacheTag, and cacheLife. Do not mix configuration-specific examples or assume every Next.js 16 project has the same caching defaults. Check the installed version and next.config before applying a recipe.

Practical implementation steps

1. Name what is being reused

Distinguish render-scoped request deduplication, persistent server data, generated route output, browser navigation state, and HTTP caches. A repeated read may disappear within one render without remaining fresh across requests. Conversely, invalidating server data does not necessarily erase a page already displayed in a browser. Trace the actual stale value to its layer before adding a broad invalidation that hides the problem.

2. Define keys and tags from data ownership

A tag identifies data that should be invalidated together; it is not an authorization boundary or a substitute for a cache key. If a reader varies by locale, tenant, or visibility, include those inputs in its key or avoid shared caching. Use stable resource-oriented tags rather than one global site tag when independent content changes should remain independent. Document who can emit the publication event.

3. Pick invalidation semantics deliberately

In Next.js 16, revalidateTag(tag, "max") marks tagged data stale and refreshes it on a later visit while allowing the stale result. updateTag expires tagged data for read-your-writes and is restricted to Server Actions. revalidatePath targets a page or layout path; it does not mean every other page using the same shared data is fresh. Match the API to the user promise and the event context.

4. Observe a correction end to end

Check the source write, authenticated event, cache invalidation, next request, listing, and open browser view. Make webhook retries safe and distinguish a committed write from a failed refresh. A refresh failure should not cause a second write merely because the frontend still displays old data. Test in production mode, since local development and hard-refresh behavior can differ from deployed cache behavior.

Implementation example

The public catalogue reader explicitly opts into shared server caching and attaches a tag. The notification function must be called only after an authenticated publication event or authorized mutation in a supported server context. Its stale-while-revalidate semantics are appropriate for a public catalogue that tolerates delay, not for confirming a just-completed private write. Example URLs are placeholders.

import "server-only";
import { revalidateTag } from "next/cache";

export async function readPublicCatalogue() {
  const response = await fetch("https://api.example.com/catalogue", {
    cache: "force-cache",
    next: { tags: ["public-catalogue"], revalidate: 3600 },
  });
  if (!response.ok) throw new Error("Catalogue unavailable");
  const value: unknown = await response.json();
  return value; // Validate the real schema before rendering.
}

export function notifyPublicCatalogueChanged() {
  revalidateTag("public-catalogue", "max");
}

Tradeoffs and alternatives

Time-based revalidation bounds ordinary staleness without requiring an event for every edit; event-based invalidation can improve correction delivery but adds authentication and retry handling. For highly sensitive or frequently changing personal data, no shared cache may be the clearer choice. Cache Components can provide a more explicit function-level model, but enabling it is a configuration migration rather than a cosmetic replacement of one function name.

Common mistakes

Do not copy the old one-argument revalidateTag example as an immediate-expiration default; that form is deprecated. Do not call updateTag from a webhook Route Handler. Do not treat router refresh as proof that all persistent server entries were invalidated. Do not cache a user-specific result under a public key, and do not label a cache tag as an access-control mechanism. Each mistake confuses a different boundary.

Production checklist

  • The article’s model matches next.config and the installed version.
  • Each cached read has freshness and visibility requirements.
  • Keys include every input affecting output.
  • Tags and paths have documented consumers.
  • Event callers authenticate and tolerate retries.
  • A saved record and an open browser view were checked separately.

FAQ

Does invalidating a path refresh shared data everywhere?

No. Path and data scopes differ. Identify other consumers and use the appropriate data tag when a change affects them. Avoid broad invalidation until the stale layer and consumer set are understood.

Which API should a CMS webhook use?

An authenticated Route Handler can use revalidateTag with a suitable profile or revalidatePath for the affected route. updateTag is restricted to Server Actions. Choose stale versus immediate-expiration behavior from the actual publication requirement.

Next step

Write a cache map for one resource, including its keys, tags, route consumers, and browser behavior. Then trace one correction through those layers. Keep public delayed-refresh behavior distinct from private read-your-writes, and revisit the map whenever authorization or locale inputs change.

Primary sources

Ihor Kharchyshyn

Independent full-stack product engineer writing source-backed implementation guides for browser extensions and modern web products.

Need this implemented in a real product?

React and Next.js applications with deliberate rendering, reliable data flows, and a clear path to production.