#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
•Question 21 of 47medium

How 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>;
}