12 min read
ā¢Question 31 of 47hardNext.js Caching Architecture
Deep dive into all four caching layers.
Next.js Four-Layer Cache
1. Request Memoization
code.txtTSX
// Same request in same render pass = single fetch
async function Component1() {
const data = await fetch('/api/user'); // Fetch 1
return <div>{data.name}</div>;
}
async function Component2() {
const data = await fetch('/api/user'); // Deduplicated!
return <div>{data.email}</div>;
}2. Data Cache
code.txtTSX
// Persistent cache on server
const data = await fetch('https://api.example.com', {
cache: 'force-cache', // Cache indefinitely (default)
// cache: 'no-store', // Never cache
next: { revalidate: 60 }, // Cache for 60 seconds
next: { tags: ['users'] }, // Tag-based invalidation
});
// Invalidate by tag
revalidateTag('users');3. Full Route Cache
code.txtTSX
// Static routes cached at build time
// Invalidation triggers:
// - revalidatePath()
// - revalidateTag()
// - Deploy
// Opt out of caching
export const dynamic = 'force-dynamic';
export const revalidate = 0;4. Router Cache (Client-side)
code.txtTSX
// Prefetched routes cached in browser
import Link from 'next/link';
// Prefetch on hover (default)
<Link href="/dashboard">Dashboard</Link>
// Disable prefetch
<Link href="/dashboard" prefetch={false}>Dashboard</Link>
// Programmatic invalidation
import { useRouter } from 'next/navigation';
const router = useRouter();
router.refresh(); // Invalidate router cacheCache Debugging
code.txtTSX
// Log cache behavior
export const fetchCache = 'default-cache';
export const revalidate = false;
export const dynamic = 'auto';
export const dynamicParams = true;