🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Caching Strategies

Next.js PerformanceđŸŸĸ Free Lesson

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.

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement