The Four Next.js Caching Layers Explained
Next.js caches more aggressively than most teams expect, and when a page serves stale data the cause is almost always one of four layers acting on a different timescale than the developer assumed. Request Memoization lives for a single render. The Data Cache persists across requests until revalidated. The Full Route Cache stores rendered HTML and payloads at build or request time. The Router Cache lives in the browser and decides how long client navigations reuse what they already have.
Understanding which layer holds your data turns cache debugging from guesswork into a checklist. This lesson defines each layer precisely, shows the exact options that control it, walks through invalidation for each, and gives you a decision table for common page types.
Prerequisites
- !Data fetching lesson: fetch options, revalidate, and tags
- !Comfort with async Server Components
- !Basic CDN and browser caching concepts
What You'll Learn
- 1Describe what each of the four caches stores and its lifetime
- 2Opt routes in and out of each cache deliberately
- 3Invalidate by time, tag, and path from application code
- 4Diagnose stale data by checking layers in order
Layer one: Request Memoization
During a single request render, identical fetch calls with the same URL and options are deduplicated. If your root layout, a nested layout, and the page each call getProduct('42'), the network request happens once and all three receive the same promise. The cache key is the full request — URL plus options — and the entry evaporates when the request finishes. There is nothing to configure; it is always on for fetch. Direct database calls through Prisma or SQL are not memoized, so shared query helpers need their own request-scoped cache if they might be called twice in one render.
Layer two: the Data Cache
The Data Cache stores fetch responses across requests and deployments until they are revalidated. Control it per call with cache and next options:
// lib/products.js
export async function getPublicProducts() {
const res = await fetch('https://api.example.com/products', {
next: { revalidate: 60, tags: ['products'] },
});
return res.json();
}
export async function getPersonalizedFeed(userId) {
const res = await fetch(`https://api.example.com/feed/${userId}`, {
cache: 'no-store',
});
return res.json();
}
export async function getPost(slug) {
const res = await fetch(`https://api.example.com/posts/${slug}`, {
next: { tags: ['posts', `post-${slug}`] },
});
return res.json();
}
Time-based revalidation refreshes in the background after the window expires, so users always get a fast cached response while the data stays reasonably fresh. Tag-based entries never expire on their own; they wait for a purge. Mixing both on one call is valid: the timer provides a safety net while tags give publishers immediate updates.
Layer three: the Full Route Cache
At build time, routes without dynamic APIs are rendered to static HTML and a flight payload, then served from the CDN. At request time, the same caching applies to routes that were not prerendered but opted into revalidation. Anything that touches cookies, headers, searchParams, or an uncached fetch opts the route out — the route becomes dynamic and renders per request.
// app/pricing/page.js — stays in the Full Route Cache
export const revalidate = 3600;
export default async function PricingPage() {
const plans = await getPlans(); // cached fetch, no cookies read
return <PricingTable plans={plans} />;
}
// app/account/page.js — always dynamic
export const dynamic = 'force-dynamic';
export default async function AccountPage() {
const user = await getCurrentUser(); // reads cookies
return <AccountDetails user={user} />;
}
The build output lists every route as static or dynamic with a reason. Reading that list after each deploy catches accidental dynamic routes before your CDN stops absorbing traffic.
Layer four: the Router Cache
In the browser, client-side navigations reuse the prefetched layout and page payloads for a short window — thirty seconds by default for page segments, longer for layouts. This is why back-navigation feels instant, and also why an admin updates a product and then navigates to its page and sees the old value. The Router Cache is client state; you control it per navigation with the router.refresh() call or by setting segment-level cache life values.
'use client';
import { useRouter } from 'next/navigation';
export default function AdminProductRow({ product }) {
const router = useRouter();
async function archive() {
await fetch(`/api/products/${product.id}/archive`, { method: 'POST' });
router.refresh(); // re-fetch server components on the current route
}
return (
<li>
{product.name}
<button onClick={archive}>Archive</button>
</li>
);
}
router.refresh() does not reload the page or reset state the way window.location does; it re-runs the server components for the current route while keeping the client tree mounted. That makes it the correct invalidation tool after mutations from client components.
On-demand invalidation across layers
Purging is where the layers meet. A route handler or Server Action that mutates data should tell every layer that the old bytes are wrong:
// app/api/products/[id]/route.js
import { revalidatePath, revalidateTag } from 'next/cache';
import { NextResponse } from 'next/server';
export async function DELETE(request, { params }) {
const { id } = await params;
await deleteProduct(id);
revalidateTag('products'); // Data Cache entries tagged products
revalidatePath('/products'); // Full Route Cache for the list page
revalidatePath('/products/[id]'); // detail pages by route pattern
return NextResponse.json({ ok: true });
}
Tag purges fix the data layer; path purges fix rendered HTML. Client-side Router Cache still holds the previous payload until the user navigates again or calls router.refresh(), which is why admin interfaces should refresh after mutations.
A decision table for common pages
| Page type | Data Cache | Full Route Cache | Router guidance |
|---|---|---|---|
| Marketing homepage | Long revalidate or build-time | Static at build | Default client cache fine |
| Product catalog | revalidate: 60 plus tags | Cached with revalidation | Refresh on category change |
| Blog article | Tag per slug | Static, purged on publish | Default |
| User dashboard | no-store | Dynamic, never cached | Avoid prefetch on private links |
| Admin tables | no-store | Dynamic | router.refresh() after edits |
Diagnosing stale data
When a page shows old content, walk the layers in order. Is the browser Router Cache returning a prefetched payload — does a hard refresh fix it? Is the Full Route Cache serving built HTML — check the build output and whether the route was forced dynamic. Is the Data Cache holding the fetch — inspect the revalidate window and whether your purge fired with the right tag. Is Request Memoization serving a duplicate within the render — usually a symptom of calling the same helper twice, not a bug. Each layer has a different fix, and naming the layer halves the time to resolution.
Production pitfalls
The traps are consistent. revalidate on a fetch inside a page that also reads searchParams never gets a chance, because the route is already dynamic. Admin users blame the app when the Router Cache shows them yesterday's edit for thirty seconds. Teams set dynamic = 'force-dynamic' globally during one debugging session and never remove it, losing all caching site-wide. And tag names drift — one module tags a response products, another purges product — so purges silently miss and the cache looks broken.
Cache keys, misses, and why identical calls diverge
When a fetch you expected to hit the cache misses, the cause is almost always the key. The Data Cache keys on the full request: URL, method, and the relevant options. Two calls that differ only in header order, a trailing slash, or a serialized body of an unused option can key differently and fetch twice. Request Memoization has the same sensitivity within a single render, which is why a shared data helper is safer than scattering inline fetch calls: one helper, one URL shape, one key. Query parameter ordering matters too. Building URLs by concatenating unsorted parameter maps produces distinct keys for semantically identical requests — a classic source of cache stampedes on pages that accept many filters. Sort your parameters, normalize your base URL, and route every call for a given resource through one function. The boring discipline of a single data module is, in practice, the most effective cache optimization available, because it turns an invisible key problem into a single reviewable file.
Common Mistakes
Setting revalidate on a fetch in a page that reads searchParams
Fix: The route is dynamic regardless; split the cacheable catalog data from the dynamic query, or cache at a higher layer.
Expecting revalidateTag to update what the browser already prefetched
Fix: Call router.refresh() after mutations, or accept that the Router Cache serves its payload until the TTL lapses.
Using force-dynamic as a permanent stale-data fix
Fix: Find which layer is wrong and purge or revalidate it; force-dynamic removes caching everywhere and moves the cost to your origin.
Inconsistent tag strings across modules
Fix: Define tag constants in one shared module so writers and purges cannot drift.
Best Practices
- Read the build output route table after every meaningful change and commit expectations to CI
- Tag every cached fetch with a domain tag plus a specific tag for fine-grained purges
- Combine time-based revalidate with tags on public data as a purge-failure safety net
- After a client-side mutation, call router.refresh() so admin views reflect the write
Interview Questions
Q1: Name the four Next.js caching layers and their lifetimes.
Request Memoization (single render), Data Cache (cross-request until revalidated), Full Route Cache (rendered HTML at build or request time until dynamic or revalidated), and Router Cache (client-side, seconds to minutes).
Q2: Why does my updated post still show for thirty seconds after publish?
The client Router Cache is serving the prefetched payload. Purge server caches with revalidateTag and revalidatePath, then router.refresh() in the client to force a fresh fetch.
Q3: What makes a route dynamic?
Reading cookies, headers, or searchParams, or issuing an uncached fetch, opts the route into per-request rendering and removes it from the Full Route Cache.
Key Takeaways
- Four layers act on different timescales: request memo, data cache, full route cache, router cache.
- Control the Data Cache with no-store, revalidate windows, and tags; purge with revalidateTag and revalidatePath.
- Dynamic APIs such as cookies and searchParams silently opt a route out of the Full Route Cache — watch the build output.
- The Router Cache is client state; router.refresh() is the correct post-mutation invalidation.
- Diagnose staleness by walking the layers from the browser inward, naming each before changing config.