Using on-demand revalidation with Next JS and Sanity, how to revalidate all paths when a specific schema type changes.
Great question! For revalidating your entire Next.js app when your navigation schema changes, you have a few solid approaches:
Best Solution: Use revalidatePath with Layout Parameter
The simplest approach is to use revalidatePath with the layout parameter, which will revalidate all routes under a given path:
import { revalidatePath } from 'next/cache'
export async function POST(req) {
// Your webhook validation logic here
// Revalidate all routes in your app
revalidatePath('/', 'layout')
return NextResponse.json({ revalidated: true, now: Date.now() })
}The 'layout' parameter tells Next.js to revalidate all pages that share that layout, which effectively means your entire app when you use '/'.
Alternative: Use revalidateTag for Navigation
If you're using tag-based revalidation, you can tag all your queries with a navigation tag and revalidate that single tag:
// In your data fetching
const data = await sanityFetch({
query: YOUR_QUERY,
tags: ['navigation', 'post'], // Add navigation tag to all queries
})
// In your revalidation API route
import { revalidateTag } from 'next/cache'
export async function POST(req) {
const body = await req.json()
if (body._type === 'navigation') {
revalidateTag('navigation') // Revalidates everything tagged with 'navigation'
}
return NextResponse.json({ revalidated: true })
}This is particularly elegant because it revalidates all pages that depend on navigation data without touching pages that don't.
Setting Up the Webhook
To trigger this automatically when your navigation changes, set up a GROQ-powered webhook in your Sanity project that filters for your navigation schema:
_type == "navigation"Point it to your Next.js API route (e.g., /api/revalidate).
The revalidatePath('/', 'layout') approach is probably your best bet since it's straightforward and ensures everything gets updated when navigation changes. Tag-based revalidation gives you more granular control if you want to optimize which pages actually get revalidated based on which content types they depend on.
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.