Skip to Content
Nextjs4.1 Caching & Revalidation

Caching & Revalidation 🧊

Next.js caches like a layered cake—every slice (request, data, route, router) has its own flavor. Mastering them keeps apps fast and fresh.

Next.js Caching Model 🧱

LayerWhat it storesScope
Request memoizationResults of identical async calls during one renderSingle request/SSR render
Data Cachefetch responses (App Router)Per fetch key + cache options
Full Route CacheHTML + payload for statically generated routesPer route segment
Router CachePrefetched client-side routesBrowser session
  • Request memoization dedupes repeated await fetch() or database calls within the same render.
  • Data Cache uses fetch caching semantics; repeated identical fetches across requests can reuse results if cacheable.
  • Full Route Cache stores static HTML (SSG/ISR) for blazing first loads.
  • Router Cache lets Next.js prefetch pages during hover/scroll.

Revalidation Strategies ♻️

Time-based (ISR)

export const revalidate = 60; // seconds
  • Applies to all fetches in the route segment.
  • Or use fetch(url, { next: { revalidate: 300 } }) per request.

On-demand (Tags / Paths)

await revalidateTag('posts'); await revalidatePath('/blog');
  • Associate fetches with tags: fetch(url, { next: { tags: ['posts'] } }).
  • Trigger invalidation after mutations or admin actions.

cache Options

  • cache: 'force-cache' → treat as static.
  • cache: 'no-store' → skip caching entirely.
  • next: { revalidate: 0 } equals dynamic.

Dynamic Rendering Triggers 🔄

Using cookies(), headers(), or reading searchParams marks a route dynamic (no full route cache) because output depends on request-specific data.

CDN + Edge Layer 🌐

  • Cache-Control headers determine CDN behavior. Example: public, s-maxage=600, stale-while-revalidate=60.
  • Vercel, CloudFront, Fastly, Cloudflare respect s-maxage (shared cache) vs max-age (browser).
  • Stale-While-Revalidate lets CDNs serve slightly old content while fetching new.
  • Cache keys should include locale, device, auth state if those change output—avoid over-broad caching that leaks data.

Analogy: caching is a grocery supply chain—request memoization is your shopping list, data cache is the pantry, full route cache is prepped meal boxes, and CDN caches are delivery hubs. Revalidation is the reminder to restock before things expire.

Last updated on