5 min read
ā¢Question 21 of 47mediumHow does caching work in Next.js?
Understanding Next.js caching strategies.
What You'll Learn
- Caching layers
- Cache invalidation
- Opting out of cache
Caching Layers
code.jsJavaScript
Request ā Router Cache ā Full Route Cache ā Data Cache ā Origin
(Client) (Server) (Server)Data Cache
code.txtTSX
// Cached indefinitely
fetch('https://api.example.com/data');
// Time-based revalidation
fetch('https://api.example.com/data', {
next: { revalidate: 3600 } // 1 hour
});
// No cache
fetch('https://api.example.com/data', {
cache: 'no-store'
});
// Tag-based
fetch('https://api.example.com/posts', {
next: { tags: ['posts'] }
});Cache Invalidation
code.txtTSX
import { revalidatePath, revalidateTag } from 'next/cache';
// Revalidate specific path
revalidatePath('/blog');
// Revalidate by tag
revalidateTag('posts');
// Revalidate layout and all children
revalidatePath('/blog', 'layout');Opting Out
code.txtTSX
// Page level
export const dynamic = 'force-dynamic';
export const revalidate = 0;
// Or use cookies/headers (makes dynamic)
import { cookies } from 'next/headers';
export default function Page() {
const cookieStore = cookies(); // Now dynamic
return <div>...</div>;
}