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

Advanced Caching

Next.js Performance🟒 Free Lesson

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.

⭐

Premium Content

Advanced Caching

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