🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Cache Tags, Revalidation, and CDN Caching Patterns

Next.js PerformanceđŸŸĸ Free Lesson

Cache Tags, Revalidation, and CDN Caching Patterns

Every caching bug is really an invalidation bug. Data that is five minutes stale is invisible in a product that changes slowly, and data that is five minutes stale after a user pressed Save is a support ticket. The skill is not knowing which header makes something fast — it is knowing, for each piece of data in your application, what event makes it wrong and how that event reaches every layer that stored a copy.

The App Router gives you several such layers, each with its own vocabulary: a data cache behind fetch, a full route cache for rendered HTML, a client-side router cache, and whatever the CDN in front of everything is configured to do. This lesson is about coordinating them rather than turning them on.

Prerequisites

  • !Server Components and data fetching
  • !HTTP caching headers at a basic level
  • !A Next.js project with a route handler you can call

What You'll Learn

  • 1Classify each data source by how it changes
  • 2Tag fetches and revalidate them from a webhook
  • 3Choose between time-based and event-based freshness
  • 4Debug a page that will not update after a deploy

Classify the data before you cache it

Two questions settle almost every decision: how often does the underlying data change, and what is the cost of a user seeing the previous value? Product prices change rarely and matter enormously, so they are candidates for event-driven invalidation rather than a timer. A view counter changes constantly and matters little, so it can be stale for a minute with nobody noticing. Personalised content is neither — it varies by user, so a shared cache must never store it in the first place.

Data shapeStrategyInvalidation triggerSafe staleness
Immutable (hashed assets)Cache foreverNever — the URL changesNone
Reference data, rarely editedTime-basedRebuild or revalidate on editMinutes to hours
Editorial contentEvent-basedPublish webhookSeconds
User-specificNo shared cachePer requestNone
Derived aggregatesStale-while-revalidateRecompute on a scheduleSeconds to minutes
Search resultsShort TTLNoneSeconds

Notice that the last two rows are explicitly allowed to be stale. Not every read needs to be correct at this instant, and pretending otherwise is how a site ends up re-rendering on every request while claiming to be cached.

Tags turn invalidation into an address

Time-based expiry asks the cache to guess when data will be wrong. Tags remove the guesswork: you label a request with the things whose change would invalidate it, and later you invalidate by label without knowing which URLs cached the result.

// app/products/[slug]/page.js — label the data by what it depends on
export async function getProduct(slug) {
  const res = await fetch(`https://api.example.com/products/${slug}`, {
    next: {
      tags: ['products', `product:${slug}`],
      revalidate: 3600, // fallback: at most one hour even if nobody invalidates
    },
  });
  if (!res.ok) throw new Error(`Product fetch failed: ${res.status}`);
  return res.json();
}

The tag list is a dependency declaration, so write it from the data's perspective rather than the page's. The product page depends on the product, its category, and the products collection; editing the product should invalidate all three views that could have rendered it — the detail page, the category listing, and the search index page — which is exactly what a well-named tag set gives you.

// app/api/revalidate/route.js — the webhook an admin panel or CMS calls
import { revalidateTag, revalidatePath } from 'next/cache';
import { NextResponse } from 'next/server';

export async function POST(request) {
  const signature = request.headers.get('x-revalidate-signature');
  const body = await request.json().catch(() => null);

  if (!body || !isValidSignature(signature, body)) {
    return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
  }

  switch (body.event) {
    case 'product.updated':
      revalidateTag(`product:${body.id}`);
      revalidateTag('products');
      break;
    case 'category.updated':
      revalidateTag(`category:${body.id}`);
      break;
    case 'page.published':
      revalidatePath(`/${body.locale}/${body.slug}`);
      break;
    default:
      return NextResponse.json({ ignored: body.event }, { status: 200 });
  }

  return NextResponse.json({ revalidated: true, at: Date.now() });
}

Two details separate a production webhook from a demo one. The signature check prevents anyone who discovers the URL from flushing your cache on demand, which is a denial-of-service vector in itself. And an unrecognised event returns success with an ignored marker rather than a 500, so a new event type added by the content team does not break their publish flow the first time.

Time-based, event-based, and both together

revalidate on a fetch sets a background revalidation interval: after the window expires the next request serves the stored value while a refresh happens behind it. That is the right default for data with no edit signal — an API you do not control, an aggregate, a leaderboard. It guarantees an upper bound on staleness even if every webhook you depend on silently stops delivering.

Events are better where they exist, because invalidation is immediate and precise instead of uniform. The pattern that holds up in practice is both: a fallback interval long enough to be a safety net, plus a webhook that shortens the real staleness to seconds. If the CMS outage takes the webhook down, your pages still refresh on the timer; when the webhook fires, users see the change at once.

// A route that must never be cached by a shared layer
export async function GET(request) {
  const session = await getSession(request);
  if (!session) return new NextResponse(null, { status: 401 });

  const usage = await getUsage(session.accountId);

  return NextResponse.json(usage, {
    headers: {
      'Cache-Control': 'private, no-store, max-age=0',
      'Vary': 'Cookie',
    },
  });
}

For route handlers that sit outside the data cache, Cache-Control is your only lever. public, s-maxage=3600, stale-while-revalidate=86400 tells a shared cache it may hold an hour of freshness and serve up to a day beyond it while refreshing — a good fit for a public catalogue endpoint. Anything personalised gets private, no-store, because a shared cache that stores one user's usage numbers will eventually serve them to another.

The client cache is a fourth copy

After the server has been invalidated, the browser may still hold the previous page in the router cache: client-side navigation reuses a prefetched segment for a short window, so a user who edits a product and clicks back sees the old one. Explicit revalidation on the server does not reach that copy.

The practical controls are few. router.refresh() re-fetches the current route from the server while preserving client state — the right call after a mutation. Setting staleTimes in the router configuration controls how long prefetched segments are reused. And for anything the user just changed, updating the client cache directly, as covered in the client fetching lesson, avoids the round trip entirely.

Debugging content that will not go stale

When a change does not appear, walk the layers outward until you find the one still holding the old value, and check in this order: the data cache (was the fetch tagged or revalidating?), the route cache (was the page statically rendered with revalidate: false?), the client router cache (is the browser reusing a prefetched segment?), the CDN (does the response carry s-maxage or x-nextjs-cache you did not intend?), and finally the browser itself (no-store versus a remembered heuristic). Adding a header that exposes which layer served the response — cache status, age, tag — turns a twenty-minute argument into a ten-second read.

The corollary worth internalising: any layer that cannot be invalidated by an event should be given a timer short enough that the maximum staleness is acceptable. Choose that number deliberately, write it next to the data classification table, and treat changing it as a product decision rather than a tuning exercise.

Proving the cache is doing anything

A caching configuration that has never been measured is a hypothesis. Verifying it takes two requests and a look at the response headers, and the exercise regularly turns up both kinds of surprise: pages you believed were shared and are not, and personalised pages that are.

# First request populates, second should be served from cache.
curl -sI https://example.com/products/blue-mug | grep -iE 'age|x-nextjs-cache|cache-control|vary'

curl -sI https://example.com/products/blue-mug | grep -iE 'age|x-nextjs-cache|cache-control|vary'

# Then confirm the invalidation path really flushes it.
curl -sX POST https://example.com/api/revalidate \
  -H 'content-type: application/json' \
  -H 'x-revalidate-signature: ...' \
  -d '{"event":"product.updated","id":"blue-mug"}'

curl -sI https://example.com/products/blue-mug | grep -iE 'age|x-nextjs-cache'

Read the three signals together. Age climbing proves a shared cache is holding the response; a cache status header naming the layer that produced it tells you which of your four copies answered; and Vary tells you whether a cookie or an accept header quietly split your audience into separate cache entries, which is the usual explanation for a cache that never seems to hit. Run the same probe against an authenticated route to confirm it comes back no-store — a 200 with a growing Age on a personalised page is a security finding, not a performance win.

Treat a cache with a zero miss rate with the same suspicion as one that never hits. A perfectly stable hit ratio usually means invalidation is not wired up at all, so every response is simply old.

Common Mistakes

Tagging by page instead of by data dependency

Fix: Label a fetch with the entities it reads; one page can depend on a dozen, and one entity backs many pages.

Exposing an unsigned revalidation endpoint

Fix: Verify a signature or secret header — an open endpoint lets anyone flush your cache whenever they like.

Assuming server revalidation clears the browser

Fix: Call router.refresh() after a mutation or update the client cache; the router cache is a separate copy.

Caching personalised responses as public

Fix: Anything varying by user must be private and unshared, with Vary set whenever a header changes the output.

Best Practices

  • Classify every data source once and record its strategy and maximum staleness
  • Give each fetch a fallback interval even when a webhook handles invalidation
  • Expose cache status headers in development so the serving layer is visible
  • Treat the revalidation webhook like any other endpoint: sign it, log it, rate-limit it

Key Takeaways

  • Caching strategy follows the data: immutable, reference, editorial, personalised and derived each behave differently.
  • Tags address cached entries by dependency, so invalidation does not need to know URLs.
  • Pair event-driven revalidation with a fallback timer so a missed webhook cannot strand stale content.
  • Shared caches need public and s-maxage; personalised responses need private and no-store.
  • There are up to four copies of any page — data cache, route cache, router cache, CDN — and debugging means naming which one is stale.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement