Originally published on tamiz.pro.
Next.js has quietly become one of the most sophisticated caching platforms in the JavaScript ecosystem — but also one of the most misunderstood. Between the Data Cache, the Full Route Cache, the Router Cache, and the client-side fetch cache, there are at least four distinct layers of caching that can interact in ways that surprise even experienced engineers. This article walks through each layer, then presents the advanced patterns that production-grade applications actually need: tag-based revalidation, time-based revalidation, cache busting with dynamic APIs, unstable_cache for custom data, and React's cache() for request memoization.
- 1. The Next.js Caching Stack: A Layered Mental Model
- 2. The Data Cache: Where Server Components Fetch
- 3. The Full Route Cache: Static Rendering, Revisited
- 4. The Router Cache: The Client-Side Layer Nobody Talks About
- 5. Advanced Pattern: Tag-Based Revalidation
- 6. Advanced Pattern: Time-Based Revalidation (ISR)
- 7. Advanced Pattern: Cache Busting with Dynamic APIs
- 8. Advanced Pattern:
unstable_cachefor Custom Data - 9. Advanced Pattern: React
cache()for Request Memoization - 10. Putting It All Together: A Production-Grade Pattern
- 11. Best Practices and Common Pitfalls
- 12. Frequently Asked Questions
1. The Next.js Caching Stack: A Layered Mental Model
Before writing a single line of cache-aware code, you need a mental model. Next.js 14+ (and the App Router in particular) does not have one cache. It has four, each with its own scope, invalidation triggers, and default behavior. The diagram below is a simplified map of how a request flows through them:
Request arrives at a route │ ▼ ┌───────────────────────┐ │ Router Cache │ ← Client-side, in-memory (per user) │ (Client Router) │ └───────────┬───────────┘ │ (if not cached) ▼ ┌───────────────────────┐ │ Full Route Cache │ ← Server-side, pre-rendered HTML/RSC payload │ (Static Route) │ └───────────┬───────────┘ │ (if not cached) ▼ ┌───────────────────────┐ │ Data Cache │ ← Server-side, fetch() results │ (fetch / DB calls) │ └───────────┬───────────┘ │ (if not cached) ▼ ┌───────────────────────┐ │ Request Memoization │ ← Per-request, dedupes identical fetch() │ (React cache) │ └───────────────────────┘ The key insight is that these layers are independent. You can invalidate one without touching the others, and their default behaviors differ dramatically. Let's examine each.
2. The Data Cache: Where Server Components Fetch
The Data Cache is the layer that stores the result of fetch() calls made inside Server Components, Route Handlers, and Server Actions. By default, in Next.js 14+, every fetch() that doesn't specify a caching strategy is cached indefinitely — even if the underlying data changes. This is a deliberate design choice: the assumption is that you will explicitly opt out when you need freshness.
Consider this seemingly innocent component:
// app/products/page.tsx import { getProducts } from '@/lib/data'; export default async function ProductsPage() { const products = await getProducts(); return ( <ul> {products.map(p => <li key={p.id}>{p.name}</li>)} </ul> ); } If getProducts() uses fetch(), the result is cached forever (until the app is rebuilt or the cache is manually purged). If it uses a direct database call (e.g. prisma.products.findMany()), it is not cached at all. This asymmetry is a frequent source of bugs.
2.1 The fetch Cache Options
Next.js extends the standard fetch API with a next option object. The three most important fields are:
| Option | Type | Description |
|---|---|---|
next.revalidate | `number \ | false` |
next.tags | string[] | Cache tags for tag-based invalidation. |
cache | `'force-cache' \ | 'no-store'` |
Example:
const res = await fetch('https://api.example.com/products', { next: { revalidate: 60, // revalidate every 60 seconds tags: ['products'], // allow revalidateTag('products') }, }); 2.2 The no-store Escape Hatch
For data that must always be fresh (user sessions, real-time prices, etc.), use no-store:
const res = await fetch('https://api.example.com/price', { cache: 'no-store', }); This bypasses the Data Cache entirely, but note that it does not bypass the Router Cache or Full Route Cache. If the page itself is statically rendered, the HTML will still be cached even if the fetch is not. This is the single most confusing aspect of Next.js caching — we'll address it in Section 7.
3. The Full Route Cache: Static Rendering, Revisited
The Full Route Cache stores the pre-rendered HTML and RSC payload for a route. It's what makes a statically rendered page load instantly on subsequent requests. By default, a route is statically rendered at build time if it doesn't use any dynamic APIs (cookies(), headers(), searchParams, noStore(), etc.).
Here's the critical nuance: the Full Route Cache is independent of the Data Cache. You can have a statically rendered page that fetches data with no-store. The page HTML is still served from the Full Route Cache — the no-store fetch happens only at build time, and its result is baked into the HTML.
3.1 Controlling Route Caching
| Mechanism | Effect |
|---|---|
export const dynamic = 'force-static' | Force static rendering, even with dynamic APIs. |
export const dynamic = 'force-dynamic' | Force dynamic rendering on every request. |
export const revalidate = 3600 | Revalidate the route every hour. |
export const dynamicParams = true/false | Controls behavior for dynamic route segments. |
Example:
// app/blog/[slug]/page.tsx export const revalidate = 3600; // revalidate this route every hour export default async function BlogPost({ params }) { const { slug } = await params; const post = await getPost(slug); return <article>{post.content}</article>; } 4. The Router Cache: The Client-Side Layer Nobody Talks About
The Router Cache is a client-side, in-memory cache of visited route segments and prefetched payloads. It lives in the browser for the duration of the session. It's what makes client-side navigation feel instant. It is not shared across users — it's per-browser.
Its invalidation is the most surprising: when you call revalidateTag() or revalidatePath() on the server, the Router Cache is not automatically invalidated on other clients. The server sends a new RSC payload, but the client may still have a stale entry in its Router Cache. You must call router.refresh() on the client to force a re-fetch of the current route.
'use client'; import { useRouter } from 'next/navigation'; export function RefreshButton() { const router = useRouter(); return ( <button onClick={() => router.refresh()}> Refresh </button> ); } 5. Advanced Pattern: Tag-Based Revalidation
Tag-based revalidation is the most powerful and most misunderstood pattern. It lets you invalidate specific data across multiple routes with a single call.
5.1 Assigning Tags
Tags can be assigned in three places:
-
fetch()calls — vianext.tags. - Route segments — via
export const revalidateorexport const dynamic. - Route Handlers / Server Actions — via
revalidateTag().
Example — a product catalog where tags are derived from the data itself:
// lib/data.ts import { unstable_cache } from 'next/cache'; export const getProduct = unstable_cache( async (id: string) => { const res = await fetch(`https://api.example.com/products/${id}`, { next: { tags: [`product-${id}`] }, }); return res.json(); }, ['product-detail'], { tags: ['products'] } ); Now, anywhere in the app, you can invalidate all products, or just one:
// app/actions.ts 'use server'; import { revalidateTag } from 'next/cache'; export async function updateProduct(id: string) { await db.product.update({ where: { id }, data: { ... } }); revalidateTag(`product-${id}`); // invalidate just this product revalidateTag('products'); // invalidate the list } 5.2 Tag Propagation
Tags propagate through the component tree. If a page fetches data with a tag, and that page is statically rendered, the tag is associated with the Full Route Cache entry as well. So revalidateTag('products') will also invalidate any route that rendered with that tag. This is the magic of tag-based revalidation: it connects the Data Cache and Full Route Cache without you having to know which routes depend on which data.
6. Advanced Pattern: Time-Based Revalidation (ISR)
Incremental Static Regeneration (ISR) is the classic pattern for content that changes predictably. It's simple to set up but has subtle edge cases.
6.1 Basic ISR
// app/blog/page.tsx export const revalidate = 300; // 5 minutes export default async function BlogIndex() { const posts = await getPosts(); return <List posts={posts} />; } On the first request, the page is generated and cached. For the next 300 seconds, every request gets the cached HTML. After 300 seconds, the first request triggers a background regeneration — the user still gets the stale page, but a new version is built in the background and replaces the cache. This is called "stale-while-revalidate."
6.2 The dynamicParams Gotcha
For dynamic routes like /blog/[slug], you need to control what happens when a new slug appears:
// app/blog/[slug]/page.tsx export const revalidate = 300; export const dynamicParams = true; // allow new slugs to be generated on-demand export async function generateStaticParams() { const posts = await getPosts(); return posts.map(p => ({ slug: p.slug })); } If dynamicParams is false, any slug not in generateStaticParams() returns a 404. If true (default), it's generated on demand and then cached with the same revalidation window.
6.3 ISR + Tags: The Hybrid
The most advanced use case combines both. You get the performance of ISR but the precision of tags:
export const revalidate = 3600; // fallback: revalidate hourly async function getDashboardData() { const res = await fetch('https://api.example.com/dashboard', { next: { tags: ['dashboard'] }, }); return res.json(); } // Later, in a Server Action: revalidateTag('dashboard'); // immediate invalidation, bypasses the 1-hour window 7. Advanced Pattern: Cache Busting with Dynamic APIs
Sometimes you need to opt a route out of the Full Route Cache entirely. The cleanest way is to use cookies(), headers(), or searchParams. When a route reads any of these, Next.js marks it as dynamic and skips the Full Route Cache.
// app/dashboard/page.tsx import { cookies } from 'next/headers'; export default async function Dashboard() { const cookieStore = await cookies(); const theme = cookieStore.get('theme')?.value ?? 'light'; const data = await getDashboardData(); // fetch is cached, but page is dynamic return <DashboardView theme={theme} data={data} />; } Important: This makes the route dynamic, but the fetch() inside is still cached in the Data Cache. If you want the data to be fresh on every request, you must also add cache: 'no-store' or revalidate: 0.
7.1 The unstable_noStore() Escape Hatch
If you want a dynamic route that fetches fresh data but you don't want to use cookies() or headers(), use unstable_noStore():
import { unstable_noStore as noStore } from 'next/cache'; export default async function LivePrice() { noStore(); // Opt out of both Full Route Cache and Data Cache const price = await fetch('https://api.example.com/price'); return <Price value={price} />; } 8. Advanced Pattern: unstable_cache for Custom Data
unstable_cache is the escape hatch for data that doesn't come from fetch(). If you're querying a database directly (Prisma, Drizzle, raw SQL, etc.), it's not cached by default. unstable_cache wraps any async function and gives it the same caching semantics as fetch().
// lib/cache.ts import { unstable_cache } from 'next/cache'; import { db } from '@/lib/db'; export const getProducts = unstable_cache( async () => { return db.product.findMany(); }, ['products'], // cache key parts { revalidate: 300, tags: ['products'] } // options ); 8.1 Key Parts and Parameterization
The second argument is an array of strings that forms the cache key. If your function takes arguments, you must include them in the key parts, or you'll get cache collisions:
export const getProduct = unstable_cache( async (id: string) => { return db.product.findUnique({ where: { id } }); }, (id) => [`product-${id}`], // ❌ WRONG — unstable_cache expects string[] ); // Correct approach: export const getProduct = unstable_cache( async (id: string) => { return db.product.findUnique({ where: { id } }); }, ['product'], // static key parts { tags: ['products'] } ); Actually, unstable_cache does not automatically parameterize by arguments. You must manually include the arguments in the key parts. The idiomatic way is to build the key parts inside the wrapper:
export const getProduct = unstable_cache( async (id: string) => { return db.product.findUnique({ where: { id } }); }, (id) => [`product-${id}`], // TypeScript allows a function returning string[] { tags: ['products'] } ); Wait — the signature accepts string[] | ((...args) => string[]). So the function form is valid. But be careful: the function must be deterministic and serializable.
8.2 The revalidate and tags Options
These work identically to the fetch options. revalidate sets the time-based window; tags allows revalidateTag() to invalidate it.
9. Advanced Pattern: React cache() for Request Memoization
React's cache() is a different beast. It's not persistent caching — it's per-request memoization. It ensures that if the same function is called multiple times during a single render, it's only executed once. This is critical for preventing duplicate database queries when the same data is needed in multiple components.
// lib/user.ts import { cache } from 'react'; export const getUser = cache(async (id: string) => { const user = await db.user.findUnique({ where: { id } }); return user; }); Now, if getUser(1) is called in a layout and a page during the same request, the database is hit only once. The result is shared within that request.
9.1 Combining cache() with unstable_cache
The real power comes from combining them. Use cache() for request-scoped deduplication, and unstable_cache for persistent caching:
import { cache } from 'react'; import { unstable_cache } from 'next/cache'; const fetchUser = unstable_cache( async (id: string) => { const user = await db.user.findUnique({ where: { id } }); return user; }, (id) => [`user-${id}`], { tags: ['users'] } ); export const getUser = cache(async (id: string) => { return fetchUser(id); }); Now the user data is persisted in the Data Cache (via unstable_cache) and deduplicated per request (via cache()). This is the optimal pattern for any server-side data access that's used in multiple components.
10. Putting It All Together: A Production-Grade Pattern
Let's build a realistic example: a product detail page that needs to be fast, but must reflect inventory changes within seconds, and must be user-specific for the "Add to Cart" button.
// app/products/[id]/page.tsx import { cookies } from 'next/headers'; import { getProduct, getRelatedProducts } from '@/lib/products'; import { AddToCart } from '@/components/AddToCart'; // 1. Route-level revalidation as a safety net export const revalidate = 300; export default async function ProductPage({ params }) { const { id } = await params; // 2. Use dynamic API to make the route dynamic for user-specific UI const cookieStore = await cookies(); const userId = cookieStore.get('userId')?.value; // 3. Fetch data with tags and short revalidation for inventory const product = await getProduct(id); const related = await getRelatedProducts(id); return ( <div> <ProductDetails product={product} /> <AddToCart userId={userId} productId={id} /> <RelatedProducts products={related} /> </div> ); } And the data layer:
// lib/products.ts import { unstable_cache } from 'next/cache'; import { cache } from 'react'; import { db } from '@/lib/db'; // Persistent cache with tags + 60s revalidation for inventory const fetchProduct = unstable_cache( async (id: string) => { const product = await db.product.findUnique({ where: { id } }); return product; }, (id) => [`product-${id}`], { revalidate: 60, tags: ['products', `product-${id}`] } ); // Request memoization to avoid duplicate queries in the same render export const getProduct = cache(fetchProduct); const fetchRelated = unstable_cache( async (id: string) => { const related = await db.product.findMany({ where: { category: (await fetchProduct(id)).category, NOT: { id } }, take: 4, }); return related; }, (id) => [`related-${id}`], { revalidate: 300, tags: ['products'] } ); export const getRelatedProducts = cache(fetchRelated); When inventory changes, a Server Action triggers:
// app/actions.ts 'use server'; import { revalidateTag } from 'next/cache'; export async function updateInventory(productId:<...

