Originally published on tamiz.pro.
Next.js ships with a powerful but often misunderstood caching model. Under the hood, the App Router coordinates four distinct caches—the Full Route Cache, the Data Cache, the Router Cache, and the Middleware Cache—each with its own lifecycle and invalidation rules. Most developers only ever touch the surface: a revalidate prop here, a fetch default there. But the real leverage lies in the advanced patterns: cache-aside with Redis, stale-while-revalidate, tag-based invalidation, on-demand ISR, and edge caching. This article walks through each pattern with production-ready code, trade-offs, and the mental model you need to avoid cache bugs that are hard to debug.
- 1. Why Server-Side Caching Matters in Next.js
- 2. The Caching Layers: A Mental Model
- 3. Data Cache: Revalidate, Tags, and Time
- 4. Full Route Cache: Static vs Dynamic
- 5. Router Cache: Client-Side Navigation
- 6. Advanced Pattern: Cache-Aside with Upstash Redis
- 7. Advanced Pattern: Stale-While-Revalidate
- 8. Advanced Pattern: Cache Tag Invalidation
- 9. Advanced Pattern: ISR with On-Demand Revalidation
- 10. Advanced Pattern: Edge Caching with Vercel KV
- 11. Production Best Practices
- Frequently Asked Questions
1. Why Server-Side Caching Matters in Next.js
Server-side caching is not an optimization afterthought—it is the backbone of a production-grade Next.js application. When you cache server-rendered content, you get three immediate benefits:
- Lower latency: Users see HTML faster because you skip database queries, external API calls, and expensive computation.
- Reduced cost: Fewer database reads and third-party API calls means lower bills, especially at scale.
- Better resilience: If your database or an upstream API goes down, a warm cache can keep serving content while you fix the root cause.
But caching also introduces a risk: stale data. The challenge is not whether to cache, but how to invalidate intelligently. Next.js gives you a rich set of primitives—revalidate, revalidateTag, revalidatePath, unstable_cache, and the fetch cache options—but they only work correctly if you understand the layer they operate on. The rest of this article builds that understanding.
2. The Caching Layers: A Mental Model
Before we dive into code, let's map out the request lifecycle in the Next.js App Router:
Browser Request │ ▼ Middleware (Middleware Cache) ── optional, per-request │ ▼ Next.js Server │ ├── Full Route Cache (RSC payload + HTML) │ └── If static: served directly │ └── If dynamic: renders on demand │ ├── Server Components │ └── Data Cache (fetch / unstable_cache) │ └── If cached: returns cached data │ └── If not: queries DB/API, stores result │ └── Router Cache (client-side, in the browser) └── Stores RSC payloads for navigations Each cache has a different scope and invalidation mechanism:
| Cache | Scope | Default TTL | Invalidation |
|---|---|---|---|
| Full Route Cache | Server, per-route | Infinite (for static) | revalidate, revalidatePath, revalidateTag, dynamic |
| Data Cache | Server, per-fetch/unstable_cache | Infinite | revalidate, revalidateTag |
| Router Cache | Browser, per-client | ~30s (dynamic) / 5min (static) | router.refresh(), revalidateTag (client components) |
| Middleware Cache | Edge, per-route | None (by default) | revalidate in middleware config |
Understanding which cache you're interacting with is the single most important skill. A common mistake is calling revalidateTag expecting it to purge the Full Route Cache, when it only purges the Data Cache. We'll see how to handle that in Section 8.
3. Data Cache: Revalidate, Tags, and Time
The Data Cache stores the results of fetch calls and unstable_cache-wrapped functions. By default, Next.js caches fetch responses indefinitely. You control it with the next option:
// app/products/page.tsx import { getProducts } from '@/lib/db'; export default async function ProductsPage() { // Cache this fetch for 60 seconds const res = await fetch('https://api.example.com/products', { next: { revalidate: 60 } }); const products = await res.json(); return ( <ul> {products.map((p) => <li key={p.id}>{p.name}</li>)} </ul> ); } But fetch only works for HTTP requests. When you need to cache a database query or a complex computation, use unstable_cache:
// lib/cache.ts import { unstable_cache } from 'next/cache'; import { getProductsFromDB } from '@/lib/db'; export const getCachedProducts = unstable_cache( async () => { // This runs only when the cache misses return getProductsFromDB(); }, ['products-list'], // cache key parts { revalidate: 300, tags: ['products'] } // 5 minutes + tag ); Then use it in a Server Component:
// app/products/page.tsx import { getCachedProducts } from '@/lib/cache'; export default async function ProductsPage() { const products = await getCachedProducts(); // ...render } Key insight: tags are the most powerful invalidation tool. You can attach multiple tags to a single cached entry, and later call revalidateTag('products') to purge every entry that carries that tag—regardless of how it was created. We'll exploit this heavily in Section 8.
4. Full Route Cache: Static vs Dynamic
The Full Route Cache stores the entire rendered route—the RSC payload and the HTML—at build time or on first request. It is the most aggressive cache and the source of many "why is my page not updating?" complaints.
By default, a route is statically rendered at build time. You can opt out per-route with dynamic:
// app/dashboard/page.tsx export const dynamic = 'force-dynamic'; export default async function Dashboard() { // This route is always rendered on request // The Full Route Cache is bypassed } Or you can enable Incremental Static Regeneration (ISR) with a time-based revalidation:
// app/blog/[slug]/page.tsx export const revalidate = 3600; // regenerate at most once per hour export default async function BlogPost({ params }) { const { slug } = await params; const post = await getPost(slug); return <article>{post.content}</article>; } Important nuance: The Full Route Cache is not just about fetch. If a route uses cookies(), headers(), or searchParams, it becomes dynamic automatically, and the Full Route Cache is skipped. That's why a page that reads cookies() for authentication will never be statically cached—even if its fetch calls are cached.
// app/profile/page.tsx import { cookies } from 'next/headers'; export default async function Profile() { const cookieStore = await cookies(); const token = cookieStore.get('auth-token'); // This route is dynamic because it reads cookies } 5. Router Cache: Client-Side Navigation
The Router Cache lives in the browser. It stores RSC payloads for pages you've visited or prefetched, so client-side navigation feels instant. It is not the same as the Full Route Cache—it's a per-client, ephemeral cache.
By default, the Router Cache has a staleTimes of 30 seconds for dynamic pages and 5 minutes for static pages. You can configure it in next.config.ts:
// next.config.ts import type { NextConfig } from 'next'; const nextConfig: NextConfig = { experimental: { staleTimes: { dynamic: 30, // seconds static: 300, // seconds }, }, }; export default nextConfig; When you call revalidateTag in a Server Action, it purges the Data Cache and the Full Route Cache, but it does not automatically purge the Router Cache. To force a client-side refresh after a mutation, call router.refresh():
// app/products/actions.ts 'use server'; import { revalidateTag } from 'next/cache'; export async function updateProduct(formData: FormData) { const id = formData.get('id'); // ...update DB revalidateTag('products'); } // app/products/ProductForm.tsx 'use client'; import { useRouter } from 'next/navigation'; import { updateProduct } from './actions'; export function ProductForm() { const router = useRouter(); return ( <form action={async (formData) => { await updateProduct(formData); router.refresh(); // Force the client to re-fetch the RSC payload }}> <input name="id" type="hidden" value="123" /> <button type="submit">Update</button> </form> ); } 6. Advanced Pattern: Cache-Aside with Upstash Redis
The cache-aside pattern is the workhorse of production caching. You check the cache first; on a miss, you load from the source, write to the cache with a TTL, and return. In Next.js, the cleanest way to implement this is inside a Server Component or Route Handler using a Redis client.
First, install the Upstash Redis client:
npm install @upstash/redis Then create a shared client:
// lib/redis.ts import { Redis } from '@upstash/redis'; export const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL!, token: process.env.UPSTASH_REDIS_REST_TOKEN!, }); Now, implement the cache-aside logic in a Server Component:
// app/products/page.tsx import { redis } from '@/lib/redis'; import { getProductsFromDB } from '@/lib/db'; export const dynamic = 'force-dynamic'; // always render fresh, but cache data export default async function ProductsPage() { const cacheKey = 'products:all'; // 1. Try cache let products = await redis.get(cacheKey); // 2. On miss, load from DB if (!products) { products = await getProductsFromDB(); // 3. Write to cache with TTL (60s) await redis.set(cacheKey, JSON.stringify(products), { ex: 60 }); } else { // 4. Parse if cached products = JSON.parse(products); } return ( <ul> {products.map((p) => <li key={p.id}>{p.name}</li>)} </ul> ); } Why use Redis instead of the built-in Data Cache? The built-in Data Cache is tied to the Next.js server lifecycle. If you deploy on a serverless platform, the Data Cache is per-instance and can be evicted. Redis is a shared, persistent cache that survives cold starts and is consistent across all serverless instances. For high-traffic apps with frequent writes, Redis is often the better choice.
Trade-off: You lose automatic tag-based invalidation unless you manually delete the Redis key. The standard approach is to delete the key in the same Server Action that mutates the data:
// app/products/actions.ts 'use server'; import { redis } from '@/lib/redis'; export async function deleteProduct(id: string) { await db.products.delete(id); // Invalidate the cache key await redis.del('products:all'); } 7. Advanced Pattern: Stale-While-Revalidate
Stale-While-Revalidate (SWR) means: serve the cached (stale) data immediately, but revalidate it in the background and swap in the fresh data when ready. This gives users the best perceived performance—no waiting for a slow database query—while still eventually showing fresh data.
Next.js's built-in revalidate option on fetch is essentially SWR. When the TTL expires, the next request triggers a background revalidation, and the stale data is served while the new data is fetched. But fetch SWR only works at the Data Cache level. To implement a more flexible SWR pattern with Redis, you can store both a timestamp and the data:
// lib/swr.ts import { redis } from './redis'; export async function getWithSWR<T>( key: string, fetchFn: () => Promise<T>, staleMs: number, revalidateMs: number ): Promise<{ data: T; isStale: boolean }> { const cached = await redis.get(key); const now = Date.now(); if (cached) { const parsed = JSON.parse(cached) as { data: T; updatedAt: number }; const age = now - parsed.updatedAt; // If data is fresh, return immediately if (age < staleMs) { return { data: parsed.data, isStale: false }; } // If data is stale but within revalidation window, serve stale + background refresh if (age < revalidateMs) { // Fire-and-forget revalidation void refreshCache(key, fetchFn); return { data: parsed.data, isStale: true }; } } // Cache miss or too old: fetch fresh const data = await fetchFn(); await redis.set(key, JSON.stringify({ data, updatedAt: now })); return { data, isStale: false }; } async function refreshCache<T>(key: string, fetchFn: () => Promise<T>) { try { const data = await fetchFn(); await redis.set(key, JSON.stringify({ data, updatedAt: Date.now() })); } catch (e) { console.error('SWR revalidation failed', e); } } Use it in a Server Component:
// app/dashboard/page.tsx import { getWithSWR } from '@/lib/swr'; import { getDashboardStats } from '@/lib/db'; export const dynamic = 'force-dynamic'; export default async function Dashboard() { const { data, isStale } = await getWithSWR( 'dashboard:stats', () => getDashboardStats(), 30_000, // serve fresh for 30s 120_000 // revalidate in background for up to 2min ); return ( <div> {isStale && <p className="text-amber-500">Updating...</p>} <Stats data={data} /> </div> ); } Why not just use next: { revalidate }? The built-in SWR is simpler, but it doesn't give you control over the stale window or the ability to signal staleness to the UI. The Redis-based SWR lets you show a subtle "Updating…" indicator and tune the revalidation window independently. It also works across serverless instances.
8. Advanced Pattern: Cache Tag Invalidation
Tag-based invalidation is the most elegant way to keep caches consistent in Next.js. The idea: attach tags to cached data, then call revalidateTag to invalidate everything associated with a tag. This is especially powerful for dynamic data that changes frequently.
Let's build a product catalog where each product has its own tag, plus a global products tag. When you update a product, you revalidate both its individual tag and the list tag:
// lib/cache.ts import { unstable_cache } from 'next/cache'; export const getProduct = unstable_cache( async (id: string) => { return db.products.findUnique({ where: { id } }); }, (id) => [`product-${id}`], // dynamic cache key { tags: ['products'] } // global tag ); export const getProductList = unstable_cache( async () => db.products.findMany(), ['product-list'], { tags: ['products'] } ); Now, in a Server Action that updates a product:
// app/products/actions.ts 'use server'; import { revalidateTag } from 'next/cache'; export async function updateProduct(id: string, data: ProductInput) { await db.products.update({ where: { id }, data }); // Invalidate the individual product AND the list revalidateTag(`product-${id}`); revalidateTag('products'); } Critical gotcha: revalidateTag purges the Data Cache and the Full Route Cache for routes that use the tagged data, but it does not purge the Router Cache. If a client component is showing stale data after a mutation, you must also call router.refresh(). In a Server Action, you can't call router.refresh() directly—you need to do it from the client component that triggered the action, as we saw in Section 5.
Another gotcha: revalidateTag only works with the built-in Data Cache. If you're using Redis for cache-aside, you must manually delete the keys. A common pattern is to combine both: use revalidateTag for the built-in cache, and also redis.del for your custom keys.
9. Advanced Pattern: ISR with On-Demand Revalidation
Incremental Static Regeneration (ISR) with on-demand revalidation lets you regenerate static pages only when the underlying data changes—not on a fixed timer. This is perfect for content-driven sites like blogs or e-commerce catalogs where you want instant updates without waiting for a TTL.
First, set up a static route with ISR enabled:
// app/blog/[slug]/page.tsx import { getPost } from '@/lib/db'; export const revalidate = false; // Disable time-based ISR; use on-demand only export async function generateStaticParams() { const posts = await getPosts(); return posts.map((post) => ({ slug: post.slug })); } export default async function BlogPost({ params }) { const { slug } = await params; const post = await getPost(slug); return <article>{post.content}</article>; } Then, create a webhook route handler that revalidates the page when the CMS updates:
// app/api/revalidate/route.ts import { NextRequest, NextResponse } from 'next/server'; import { revalidatePath, revalidateTag } from 'next/cache'; export async function POST(request: NextRequest) { const body = await request.json(); const { slug...
