revalidatePath() & revalidateTag()

Invalidate the Cache From Server Actions

revalidatePath() & revalidateTag()

Call `revalidatePath` or `revalidateTag` from Server Actions and Route Handlers to bust cached data after a mutation.

4 min read Level 3/5 #nextjs#revalidate#caching
What you'll learn
  • Call `revalidatePath('/posts')` after inserting a post
  • Call `revalidateTag('posts')` to invalidate by content type
  • Combine tags with cache for targeted refreshes

After a mutation — a new post, an updated profile, a deleted comment — the cached data on the server is stale. revalidatePath and revalidateTag are the two functions that tell Next.js to refetch on the next request.

revalidatePath

Bust the cache for a specific route. Subsequent visits to that route re-run data fetches.

'use server'
import { revalidatePath } from 'next/cache'
import { db } from '@/lib/db'

export async function createPost(form: FormData) {
  await db.posts.insert({ title: String(form.get('title')) })
  revalidatePath('/posts')
}

The next time someone visits /posts, the data refetches. Without this, the list shows yesterday’s results until the cache TTL expires.

revalidateTag

If multiple pages share the same data, tag the fetch and invalidate by tag instead.

'use server'
import { revalidateTag } from 'next/cache'

export async function publishPost(id: string) {
  await db.posts.update(id, { published: true })
  revalidateTag('posts') // every fetch with tag 'posts' is now stale
}

Pair it with the fetch tag from the previous lesson:

await fetch('/api/posts', { next: { tags: ['posts'] } })

Picking Between Them

Use revalidatePath when the change affects one route. Use revalidateTag when the data is shared across many routes (a navbar count, a feed shown in two places, etc.).

Streaming & Suspense →