πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Caching Patterns

Next.js Performance🟒 Free Lesson

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.

⭐

Premium Content

Caching Patterns

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement