Next.js Performance

Caching Patterns

Cache strategies, invalidation, stale-while-revalidate, and CDN caching.

Advertisement

Caching Patterns

Cache strategies, invalidation, stale-while-revalidate, and CDN caching.

Overview

Effective caching improves performance and reduces server load.

Key Concepts

  • Cache-Aside — Application manages cache
  • Write-Through — Update cache on write
  • Stale-While-Revalidate — Serve stale while updating
  • CDN Caching — Edge caching for static content
  • Cache Invalidation — Keep cache fresh

Code Examples

// Cache with tags
async function getProducts(category) {
  const res = await fetch(`https://api.example.com/products?category=${category}`, {
    next: { tags: ['products', `category-${category}`] }
  });
  return res.json();
}

// On-demand revalidation
// app/api/revalidate/route.js
import { revalidateTag, revalidatePath } from 'next/cache';

export async function POST(request) {
  const { type, id } = await request.json();

  if (type === 'product') {
    revalidateTag('products');
    revalidateTag(`category-${id.category}`);
    revalidatePath(`/products/${id}`);
  }

  if (type === 'page') {
    revalidatePath(id);
  }

  return Response.json({ revalidated: true });
}

// CDN caching with headers
export async function GET(request) {
  const data = await fetchData();
  
  return Response.json(data, {
    headers: {
      'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400'
    }
  });
}

// Client-side caching with SWR
'use client';
import useSWR from 'swr';

function ProductList() {
  const { data, error } = useSWR('/api/products', fetcher, {
    revalidateOnFocus: false,
    dedupingInterval: 60000
  });

  return <List items={data || []} />;
}

Practice

Implement multi-layer caching with CDN, server, and client caching.