पाठ 13 / 25

Revalidation

Refresh cached content after changes.

Time-based and on-demand

Time-based revalidation refreshes cached data after a period (a cache lifetime, or revalidate seconds in the previous model). On-demand revalidation refreshes immediately after a change: revalidatePath("/products") marks a route's cached output as stale, and revalidateTag("products") (with updateTag for read-your-own-writes in the newer model) invalidates every cached entry tagged with that name. Call these from Server Actions or Route Handlers after mutations so users see fresh data. Next.js changes quickly between major versions; check the docs for your version (they ship inside node_modules/next/dist/docs).

Revalidating after a change

A typical pattern inside a Server Action; not part of the built demo.

"use server";
import { revalidatePath, revalidateTag } from "next/cache";

export async function updatePrice(id: string, price: number) {
  await db.product.update({ where: { id }, data: { price } });
  revalidateTag("products");          // every cached query tagged "products"
  revalidatePath(`/products/${id}`);  // the product page itself
}

Revalidate where you mutate

Put revalidation calls next to the write, so no code path updates data without refreshing caches.

त्वरित जाँच: When should you call revalidatePath or revalidateTag?

  • On every page view
  • Right after a mutation that changes the cached data
  • Never; caches update themselves instantly
  • Only during the build
Answer

Right after a mutation that changes the cached data — Invalidate caches when data changes.