Sanity Webhook Revalidation: Batching Tags in Next.js

By Nayan Kyada · · 7 min read

Part of The Sanity + Next.js Guide

The problem: one webhook per document balloons deploy traffic

When a Sanity editor publishes ten blog posts in a row, the default webhook setup fires ten separate POST requests to your Next.js revalidate endpoint. Each triggers an ISR purge. On a serverless host that's ten function invocations and ten separate cache invalidations, many of them redundant — the blog index gets purged ten times for one editing session.

Sanity's webhook settings don't offer a debounce, and even a debounce wouldn't solve the core issue: Next.js On-Demand Revalidation expects you to name every path or tag you want to purge. If your blog index depends on all posts, you end up either revalidating /blog once per post (redundant) or writing brittle logic to figure out which paths changed.

Use revalidateTag and a single Sanity webhook

Instead of per-document webhooks, I register one Sanity webhook that POSTs a small _type/_id/slug payload to a single Next.js route handler. The handler revalidates a tag, not a path. Here's the setup.

First, the route handler at app/api/revalidate/route.ts:

// app/api/revalidate/route.ts
import { revalidateTag } from 'next/cache';
import { NextRequest, NextResponse } from 'next/server';
import { parseBody } from 'next-sanity/webhook';
 
const SANITY_REVALIDATE_SECRET = process.env.SANITY_REVALIDATE_SECRET!;
 
export async function POST(req: NextRequest) {
  // parseBody validates the HMAC signature itself when given the secret —
  // it returns { body, isValidSignature }, not the body directly. Passing
  // just `req` (no secret) skips verification silently, which is the most
  // common mistake copying this helper from older examples.
  const { body, isValidSignature } = await parseBody<{ _type: string; _id?: string; slug?: string }>(
    req,
    SANITY_REVALIDATE_SECRET,
  );
 
  if (!isValidSignature) {
    return NextResponse.json({ message: 'Invalid signature' }, { status: 401 });
  }
  if (!body?._type) {
    return NextResponse.json({ message: 'Missing _type' }, { status: 400 });
  }
 
  const tags = [`sanity:${body._type}`];
  if (body.slug) tags.push(`sanity:${body._type}:${body.slug}`);
 
  // { expire: 0 } expires immediately — what an external webhook usually wants.
  // (The single-argument revalidateTag(tag) form is deprecated in Next.js 16.)
  tags.forEach((tag) => revalidateTag(tag, { expire: 0 }));
 
  return NextResponse.json({
    revalidated: true,
    tags,
    now: Date.now(),
  });
}

Create the webhook in your project settings at sanity.io/manage (API → Webhooks). The URL is just the endpoint — no secret in the query string, because parseBody verifies the signature Sanity adds when you set the webhook's Secret field to the same value as SANITY_REVALIDATE_SECRET:

https://yourdomain.com/api/revalidate

The payload is defined by a GROQ projection:

{ _type, _id, "slug": slug.current }

Trigger on Create, Update, Delete for all document types.

Tag data fetches by document type, not by path

Now, any Server Component that fetches Sanity data must declare the tag in the fetch options. For a blog index:

// app/blog/page.tsx
import { client } from '@/sanity/client';
 
export default async function BlogIndexPage() {
  const posts = await client.fetch<Post[]>(
    `*[_type == "post" && !(_id in path("drafts.**"))] | order(publishedAt desc) [0...20] {
      _id, title, slug, publishedAt, "author": author->name
    }`,
    {},
    {
      next: {
        tags: ['sanity:post'],
      },
    }
  );
 
  return (
    <div>
      {posts.map((p) => (
        <article key={p._id}>
          <h2>{p.title}</h2>
        </article>
      ))}
    </div>
  );
}

When an editor publishes a new post, the webhook fires once, revalidates sanity:post, and Next.js purges every fetch tagged with that label. No per-path logic. No race conditions.

For a single post page, I tag only that document (you can't use post._id in the tag — it doesn't exist until the fetch returns — so key it on the slug the webhook also sends):

// app/blog/[slug]/page.tsx
import { client } from '@/sanity/client';
 
export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const post = await client.fetch<Post>(
    `*[_type == "post" && slug.current == $slug][0] {
      _id, title, body, publishedAt
    }`,
    { slug },
    {
      next: {
        tags: [`sanity:post:${slug}`],
      },
    }
  );
 
  return <article>{post.title}</article>;
}

This ensures that if an editor updates a specific post, only that post's page and the index (tagged sanity:post) purge. Other post pages remain cached. If a post page also renders data from other types — related posts, author bios — add those types' tags too. And if an editor changes a slug, the old URL's tag won't be hit; handle renames with a redirect.

Why this cuts webhook noise

Sanity doesn't batch webhooks: a bulk publish of 80 posts still sends 80 requests (one at a time — Sanity limits webhooks to one concurrent request). What changes is the work each request does. With per-path logic, each request has to work out and purge every affected route, so the blog index and listing pages are re-rendered over and over. With tags, each request does two cheap revalidateTag calls, and Next.js only regenerates a tagged page the next time it's requested — the index is rebuilt once, not 80 times.

The result is fewer redundant regenerations, simpler handler code, and no per-path mapping to keep in sync with your routes.

Gotchas

If your homepage aggregates multiple document types (posts, projects, testimonials), you must tag the fetch with all relevant types:

{
  next: {
    tags: ['sanity:post', 'sanity:project', 'sanity:testimonial'],
  },
}

Any publish of those types will purge the homepage. If you forget a tag, the page won't revalidate and editors will report stale data.

Also, revalidateTag only purges the Next.js cache. If you put your own CDN like Cloudflare or Fastly in front of your host, you'll need a separate purge call to their API — make it from the same route handler, right after the revalidateTag calls, for the URLs or cache tags affected.

When not to use this

If your Sanity dataset has 10,000+ documents and your pages aggregate data from hundreds of types, tagging every type on every page becomes unwieldy. In that case, consider PPR or a time-based ISR with revalidate: 60 instead of on-demand revalidation. For most marketing and editorial sites under 1,000 pages, tag-based revalidation is the sweet spot.

Surviving bulk operations

The single-webhook design has a stress case: bulk publishes. An editor imports 80 documents from a migration script, Sanity queues 80 webhooks and delivers them one after another, and the route handler dutifully revalidates the same handful of tags 80 times. Nothing breaks — revalidation is idempotent — but you burn function invocations at exactly the moment a migration is watching for errors.

The fix is a debounce keyed on the tag set. Since serverless functions can't hold state between invocations, park the pending tags somewhere shared with a short TTL — Upstash Redis or Vercel KV both work:

import { after } from "next/server";
 
// Collapse a burst: only the invocation that wins the lock revalidates.
const tags = tagsForDocument(body._type);
await kv.sadd("pending-tags", ...tags);
 
const locked = await kv.set("reval-lock", "1", { nx: true, ex: 10 });
if (locked) {
  // Respond right away so Sanity can deliver the next webhook (it sends one
  // at a time), and flush the accumulated tags after the response is sent.
  after(async () => {
    await sleep(8000); // let the burst accumulate
    const batch = await kv.smembers("pending-tags");
    await kv.del("pending-tags");
    batch.forEach((t) => revalidateTag(t, { expire: 0 }));
  });
}
return NextResponse.json({ queued: tags });

Eighty webhooks become one revalidation pass roughly eight seconds after the burst starts. Don't sleep before responding: because Sanity delivers one webhook at a time, a handler that blocks for eight seconds just delays the next delivery instead of letting a burst accumulate. The trade-off is explicit: you've added up to ~10 seconds of staleness in exchange for collapsing the fanout — the right trade for content types where a migration burst is even possible.

Worth being honest about the threshold, though: at normal editorial cadence — a few publishes an hour — the debounce is pure overhead, another moving part and a KV dependency you now operate. I add it only once a project actually has bulk import workflows or scheduled mass publishes on the roadmap. The base pattern from this post stays the default; the debounce is the escape hatch for the day an editor pastes a spreadsheet into a script.

Frequently asked questions

What is SANITY_REVALIDATE_SECRET for?

It's a shared secret you generate yourself and put on both sides: as the webhook secret in your project's API → Webhooks settings at sanity.io/manage, and as an environment variable passed into `next-sanity/webhook`'s `parseBody(req, secret)` on your route handler, which uses it to verify the request's HMAC signature. Without it, anyone who discovers your `/api/revalidate` endpoint could trigger arbitrary cache purges — it's authentication for the webhook, not a Sanity-provided value.

Should I revalidate by path or by tag when using Sanity webhooks with Next.js?

By tag. Path-based revalidation forces you to enumerate every route affected by a document change, which gets brittle fast when an index page depends on many documents. Tagging fetches with `sanity:${_type}` (and a document-specific tag such as `sanity:post:${slug}` for single-document pages) lets one webhook call purge every affected page with a couple of `revalidateTag()` calls, with no per-path logic to maintain.