CodePark/ questions / Data fetching & caching
START PRACTICINGPRACTICE
Frontend question · Next.js › Data fetching & caching

Explain time-based versus on-demand revalidation.

// fetch with a lifetime and a tag
const posts = await fetch("https://cms.example.com/posts", {
  next: { revalidate: 3600, tags: ["posts"] },
});

// app/actions.ts
"use server";
import { revalidateTag } from "next/cache";
export async function publish() {
  await savePost();
  revalidateTag("posts");
}

Time-based revalidation refreshes cached data after a fixed time. On-demand revalidation refreshes it the moment you say the data changed.

Time-based. You set a lifetime for cached data in seconds:

  • on a request: fetch(url, { next: { revalidate: 3600 } })
  • on a route: export const revalidate = 3600

It works like stale-while-revalidate: serve the old copy now, and fetch a fresh one in the background. After the time window ends, the next request still gets the stale version. That request also starts regeneration in the background. Later requests get the fresh data.

On-demand. You clear cache entries when something changes. You usually do this from a Server Action, or from a Route Handler that a CMS webhook calls.

  • revalidatePath("/blog") invalidates a route.
  • revalidateTag("posts") invalidates every fetch tagged with posts.

When to use which. Use time-based for data that changes on a predictable schedule, when perfect freshness isn't critical, like a weather widget. Use on-demand when you know exactly when data changes and want it visible at once, like a blog post just published.

  • Time-based revalidation uses a revalidate value in seconds and works like stale-while-revalidate.
  • The first request after expiry still gets stale data and starts a refresh.
  • On-demand revalidation uses revalidatePath or revalidateTag.
  • On-demand revalidation is triggered from Server Actions or webhooks.