Next.js Performance

Advanced Caching

Cache tags, on-demand revalidation, cache invalidation patterns, and CDN caching.

Advertisement

Advanced Caching

Cache tags, on-demand revalidation, cache invalidation patterns, and CDN caching.

Overview

Advanced caching patterns optimize performance for complex applications.

Key Concepts

  • Cache Tags — Fine-grained cache control
  • On-Demand Revalidation — Invalidate cache via API
  • Cache Invalidation — Patterns for keeping data fresh
  • CDN Caching — Edge caching for static content
  • Stale-While-Revalidate — Serve stale while updating

Code Examples

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

async function getPosts() {
  const res = await fetch('https://api.example.com/posts', {
    next: { tags: ['posts'] }
  });
  return res.json();
}

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

export async function POST(request) {
  const { tag, path } = await request.json();
  
  if (tag) {
    revalidateTag(tag);
  }
  
  if (path) {
    revalidatePath(path);
  }
  
  return Response.json({ revalidated: true, timestamp: Date.now() });
}

// Webhook for CMS updates
// app/api/webhook/route.js
export async function POST(request) {
  const { event, entity } = await request.json();
  
  switch (event) {
    case 'post.published':
      revalidateTag('posts');
      revalidatePath('/blog');
      revalidatePath(`/blog/${entity.slug}`);
      break;
    case 'post.deleted':
      revalidateTag('posts');
      revalidatePath('/blog');
      break;
  }
  
  return Response.json({ received: true });
}

Practice

Implement cache invalidation for a CMS-powered blog with webhooks.