Caching & Revalidation

Next.js tries to be as aggressive as possible to make your application fast. By default, it automatically caches the results of data fetches and even entire route HTMLs upon building. However, when data changes (e.g. someone edits a blog post), you need a way to bust that cache efficiently.

Time-based Revalidation (ISR)

You can instruct Next.js to revalidate the cache of a specific fetch request automatically after a set interval (in seconds).

// Triggers a background refresh at most once every 60 seconds
const res = await fetch('https://api.example.com/posts', {
  next: { revalidate: 60 }
});

On-Demand Revalidation (`revalidatePath`)

Waiting 60 seconds isn't always ideal. If an Admin saves a new Product, they expect to see it on the website immediately! Inside a Server Action or an API Route Handler, you can instantly break the cache for a specific route path.

'use server';
import { revalidatePath } from 'next/cache';

export async function createProduct(formData) {
  await db.products.insert(formData);
  
  // This instantly purges the cache for '/shop'. 
  // Next time a user visits, the server generates fresh HTML.
  revalidatePath('/shop'); 
}

Tag-based Revalidation (`revalidateTag`)

In massive architectures, you might display the exact same product data on multiple different UI pages (Homepage, Shop page, Profile history). Revalidating all those paths manually is tedious. Instead, you can tag a fetch request with a name, and later purge ALL caches across the entire site that share that tag!

// 1. Tag your fetch request
const res = await fetch('https://api.example.com/products/123', {
  next: { tags: ['product-123'] }
});

// -------------

// 2. In your Server Action later...
'use server';
import { revalidateTag } from 'next/cache';

export async function updateProductDetails() {
  await db.update();
  
  // Instantly regenerates EVERY page across the site that fetched 'product-123'!
  revalidateTag('product-123');
}

Conclusion

Mastering `revalidatePath` and `revalidateTag` allows you to deliver 100% statically generated sites (blazing fast load speeds) without sacrificing real-time updates. Finally, let's look at TypeScript Integration.