Topic 40 of 47
Cache Layer Invalidation
Overview
When you fetch data statically using Next.js's extended fetch API, the result is cached. To ensure users see fresh data after mutations (like adding a post), you must invalidate (purge) this cache using `revalidatePath` or `revalidateTag`.
Syntax
tsx
import { revalidatePath, revalidateTag } from 'next/cache';
// Revalidate all data fetching calls associated with a specific route path
revalidatePath('/blog'); // Clears cache for the /blog page
// Revalidate only specific fetch calls using tags
// Given a fetch call like: fetch(url, { next: { tags: ['posts'] } })
revalidateTag('posts'); // Clears cache for ANY fetch tagged with 'posts'Common Pitfalls
- Cache invalidation (`revalidatePath`/`revalidateTag`) only works when called from Server Actions or Route Handlers. You cannot call them directly from Client Components.
- Revalidating a path does not immediately refresh the page for the user who made the mutation unless combined with router.refresh() or redirect().
Real-World Example
Invalidating cache inside a Server Action after creating a new item:
example
tsx
// app/actions/addPost.ts
'use server';
import { revalidateTag } from 'next/cache';
export async function addPost(formData: FormData) {
const title = formData.get('title');
// 1. Perform database mutation
await db.posts.insert({ title });
// 2. Invalidate the cache for the posts list
// The next user to visit the page will trigger a fresh fetch
revalidateTag('posts');
}