Revalidation and Cache Invalidation in Next.js


Cache invalidation has a famous reputation because it is often treated as an afterthought: data changes, a route looks stale, and someone adds a broad refresh until the symptom disappears. In a production App Router application, invalidation deserves a clearer model. A mutation changes a domain record; the application has a defined freshness promise for each reader of that record; the cache mechanism enforces that promise with a target and a delivery behaviour.
The useful question is not “how do I clear the cache?” It is “who must see this change, when, and what data or route boundary represents that promise?”
Freshness Is a Product Contract
Different changes need different consistency experiences. When a person changes their cart, they reasonably expect the next screen to show the new cart. When an editor updates a public article, serving a recently cached version while refresh happens in the background may be acceptable. When a route must be refreshed after a structural deployment change, path scope may be the right unit.
Write the promise down before choosing an API:
| Mutation | Readers | Freshness expectation | Candidate |
|---|---|---|---|
| Add item to current user’s cart | The actor | Immediate read-your-own-write | updateTag in a Server Action |
| Publish a documentation change | Public readers | Briefly stale content acceptable | revalidateTag(tag, "max") |
| Refresh a one-off route surface | Visitors to one route | Next visit gets refreshed route data | revalidatePath |
The current Next.js revalidating guide (opens in new tab) recommends tag-based invalidation where possible because tags target domain data precisely. Paths are still useful, but they describe a rendering surface rather than every consumer of a data entity.
Tag Cached Data by Domain Ownership
Tags are most useful when they are domain vocabulary, not a list of page names. A product cache can have a collection tag and an item-specific tag; a mutation can invalidate only the relevant item or the broader collection when the mutation changes list membership.
import { cacheTag } from "next/cache";
export async function getProduct(id: string) {
"use cache";
cacheTag("products", `product:${id}`);
return db.product.findUniqueOrThrow({ where: { id } });
}The tags express ownership and scope: product:42 is the precise entity; products represents consumers of the collection. Do not put unbounded user input, secrets, or a full serialized query in tags. They are identifiers your team will need to reason about during an incident.
For fetch, tags can be attached with next.tags; for use cache functions or components, use cacheTag. The cacheTag reference (opens in new tab) notes that tags are idempotent, can be assigned in multiples, and have item and length limits. Keep a small tag-construction helper so spelling and scoping do not drift through the codebase.
export const productTags = {
all: "products",
byId: (id: string) => `product:${id}`,
};Choose the Invalidation Primitive
Next.js has three complementary operations, each with a distinct delivery contract.
Choose a freshness contract
Switch among the primary invalidation primitives to compare scope and user-visible behaviour.
Invalidation strategy explorer
Select the contract that fits the mutation and freshness expectation.
Server Actions; tagged data across consumers
Expires the tag for read-your-own-writes: the next request waits for fresh data rather than receiving stale content.
"use server";
await updateCart(input);
updateTag(cartTag(userId));updateTag: immediate read-your-own-writes
Use updateTag from a Server Action when the actor must see their mutation immediately. It expires the tag so the next request waits for fresh data rather than serving stale content.
"use server";
import { updateTag } from "next/cache";
export async function changeCartQuantity(input: CartInput) {
const user = await requireUser();
await carts.changeQuantity({ userId: user.id, ...input });
updateTag(`cart:${user.id}`);
}The updateTag reference (opens in new tab) is explicit about its Server Actions-only scope. Do not call it from a Route Handler or Client Component; that limitation reinforces its purpose as a user-initiated mutation path.
revalidateTag: stale while revalidating
Use revalidateTag(tag, "max") when fresh content matters but a short stale window is acceptable. This is a good match for public catalog, documentation, and editorial content. The recommended "max" profile marks tagged values stale, serving the existing value while a fresh result is fetched in the background on the next visit.
import { revalidateTag } from "next/cache";
export async function POST(request: Request) {
await verifyCmsWebhook(request);
revalidateTag("documentation", "max");
return Response.json({ ok: true });
}The revalidateTag documentation (opens in new tab) warns that the single-argument form is deprecated. Use the explicit profile and explain why stale-while-revalidate matches the product expectation.
revalidatePath: a route-surface refresh
Use revalidatePath for a page, layout, or route-handler path when path scope is exactly what you need. It does not invalidate other pages that read the same tagged data. If a product appears on both /products/[slug] and /dashboard, refreshing only the product path leaves the dashboard’s cached product reader untouched; invalidate a product tag as well when cross-route consistency matters.
import { revalidatePath, updateTag } from "next/cache";
export async function updateProduct(input: ProductInput) {
const product = await products.update(input);
updateTag(`product:${product.id}`);
revalidatePath(`/products/${product.slug}`);
}The revalidatePath reference (opens in new tab) documents this distinction and the difference between a specific URL and a dynamic route pattern. Think of tags and paths as complementary, not competing, when one mutation changes both domain data and a particular rendered route.
Sequence Mutations Before Invalidations
The ordering rule is non-negotiable: validate and authorize, commit the mutation, then invalidate. Invalidating before a write commits can trigger a refresh that reads old data and repopulates the cache with precisely the value you meant to replace.
authenticate → validate input → authorize resource → commit mutation
→ invalidate precise data tags → refresh required path → respondUse transactions or an outbox pattern when a mutation crosses systems. If your database writes successfully but a webhook-driven invalidation fails, you need a durable way to retry invalidation without repeating the write. A best-effort catch that logs and returns success turns a consistency failure into a support mystery.
Invalidate Only After Authorization
Cache keys and invalidation endpoints are operational capabilities. Protect webhook and Route Handler invalidation paths with authentication, signature verification, input validation, rate limits, and a narrow allowlist of tags or paths. Never let a public query parameter flush arbitrary cache surfaces.
Test the Whole Consistency Story
The route that performed a mutation is not the only reader to test. Build a small consistency matrix for every important domain change:
- Seed the old value and confirm every relevant route initially reads it.
- Perform the authorized mutation through its actual Server Action or webhook path.
- Verify the actor sees the promised freshness behaviour.
- Visit another route using the same entity and verify its tag/path expectation.
- Attempt an unauthorized mutation and verify neither data nor cache state changes.
- Simulate an invalidation delivery failure and verify retry/alerting behaviour.
Add instrumentation around mutation id, tag/path target, cache outcome, trace id, and response freshness. During an incident, “we called revalidateTag” is weaker evidence than a trace showing which exact tag was assigned to which cached function, which webhook was verified, and which reader fetched the new revision.
Key Takeaways
- Design invalidation from the user-visible freshness promise, not from a desire to clear cache broadly.
- Tag cached data with stable domain ownership so a mutation can target the right readers across routes.
- Use
updateTagfor Server Action read-your-own-writes,revalidateTag(tag, "max")for stale-while-revalidate, andrevalidatePathfor a specific route surface. - Commit authorized mutations before invalidating, and make cross-system invalidation retryable and observable.
- Test every important mutation across all routes and users that read the changed domain data.
Next, we will use these freshness foundations to build Server Actions that are secure, observable, progressively enhanced, and deliberate about the boundary between a form submission and a privileged mutation.