Group Cached Data, Invalidate by Topic
Cache Tags & revalidateTag
Tag fetches with strings, then invalidate every cached entry with a tag in a single call from a Server Action.
What you'll learn
- Tag a fetch with `next.tags`
- Call `revalidateTag` from a Server Action
- Coordinate cache busts across pages that share data
Tags are labels you attach to cached fetches so you can invalidate them as a group later. They are the most flexible cache-busting tool Next ships.
Tag the Fetches
// app/posts/page.tsx
const posts = await fetch('https://api.example.com/posts', {
next: { tags: ['posts'] },
}).then((r) => r.json())
// app/post/[id]/page.tsx
const post = await fetch(`https://api.example.com/posts/${id}`, {
next: { tags: ['posts', `post-${id}`] },
}).then((r) => r.json()) A fetch can have multiple tags. Both calls are tagged posts; the single-post call is
also tagged with its specific ID.
Invalidate From an Action
// app/actions.ts
'use server'
import { revalidateTag } from 'next/cache'
export async function publish(id: string) {
await db.post.update({ where: { id }, data: { published: true } })
revalidateTag('posts')
revalidateTag(`post-${id}`)
} revalidateTag('posts') drops every Data Cache entry tagged posts. The next request
to any page that depends on those fetches re-runs them.
Tags vs Paths
revalidatePath('/posts') says “this URL is stale”. revalidateTag('posts') says
“this slice of data is stale”, regardless of which URLs depend on it. When the same
data appears on many pages, tags scale better — you do not have to remember every URL.