Next.js Performance

Caching Strategies

Data cache, full route cache, router cache, and cache invalidation.

Advertisement

Caching Strategies

Data cache, full route cache, router cache, and cache invalidation.

Overview

Next.js has multiple caching layers for optimal performance.

Key Concepts

  • Data Cache — Cache fetched data across requests
  • Full Route Cache — Cache entire routes on server
  • Router Cache — Client-side route prefetching
  • Revalidation — Time-based or on-demand invalidation
  • Cache Tags — Fine-grained cache control

Code Examples

// Data Cache with revalidation
async function getProducts() {
  const res = await fetch('https://api.example.com/products', {
    next: { revalidate: 3600 } // Cache for 1 hour
  });
  return res.json();
}

// Cache with tags for selective invalidation
async function getUser(id) {
  const res = await fetch(`https://api.example.com/users/${id}`, {
    next: { tags: [`user-${id}`, 'users'] }
  });
  return res.json();
}

// app/api/revalidate/route.js
import { revalidateTag } from 'next/cache';

export async function POST(request) {
  const { tag } = await request.json();
  revalidateTag(tag);
  return Response.json({ revalidated: true });
}

// Force dynamic route (no cache)
async function DynamicPage() {
  const data = await fetch('https://api.example.com/data', {
    cache: 'no-store' // Always fresh
  });
  return <div>{data}</div>;
}

// Opt out of full route cache
export const dynamic = 'force-dynamic';

Practice

Implement cache invalidation for a product catalog with different strategies.