DEV Community

Cover image for Stop Hitting the Sanity API on Every Request: Build Smart Caching with Next.js ISR and Webhooks
Jay Patel
Jay Patel

Posted on Edited on Originally published at jaypateldev.com

Stop Hitting the Sanity API on Every Request: Build Smart Caching with Next.js ISR and Webhooks

Your blog feels fast in development. Then real traffic arrives, and every page view sends a fresh GROQ query to Sanity. Response times grow, the API usage chart climbs, and nobody chose this on purpose. It happens when fetch calls have no cache plan.

Sanity caching in Next.js fixes this by storing query results and clearing them only when content changes. In this guide, I share the setup I use for read-heavy sites. It uses ISR as a safety net, cache tags for precision, and a signed webhook that refreshes pages seconds after an editor clicks publish. If you want help applying this to a live product, our full stack development services cover Next.js and headless CMS builds.

We will build it in layers: a folder structure, a cached fetch helper, tag design, a webhook route, database logging, error handling, and a production checklist. The code targets Next.js 15 and 16 with the next-sanity package.

Understanding the Request Flow of Sanity Caching in Next.js

A visitor opens a post. Before Sanity is ever asked, two caches get a chance to answer. A request reaches the Sanity origin only if neither caching layer returns a result. Knowing this path helps you decide where each rule belongs.

Next.js Data Cache and ISR with Sanity

Next.js Data Cache handles the initial stage of content retrieval. When you pass revalidate and tags to a fetch call, Next.js stores the result on your server. The next visitor gets that stored copy without any network call to Sanity.

ISR works on top of this. After the revalidate time ends, Next.js serves the old copy once and rebuilds a fresh one in the background. Readers never wait for the rebuild. That is why the time value acts as a safety net, not the main refresh method.

Sanity API CDN for Published Content

Sanity API CDN provides an additional caching stage after the Next.js Data Cache. When you create the client with useCdn: true, published queries are served from the edge when possible. This is the right choice for public pages.

Draft content is different. Since drafts require a token and useCdn: false, configure a dedicated client for draft content instead of sharing your public client. Mixing them is a common way to leak unpublished text or pollute the cache.

Project Structure That Keeps Cache Rules in One Place

Caching logic scattered across pages becomes impossible to audit. I keep every rule in a small lib folder, so a reviewer can read the whole strategy in minutes.

app/

blog/[slug]/page.tsx

api/revalidate/sanity/route.ts

lib/

sanity/client.ts

sanity/fetch.ts

sanity/queries.ts

cache/tags.ts

db.ts
⭐ Football Update: jaypateldev/stop hitting the sanity api on every request build smart caching with nextjs isr and webhooks d - Pertandingan Hari Ini ⭐ Football Update: jaypateldev/stop hitting the sanity api on every request build smart caching with nextjs isr and webhooks d - Pertandingan Hari Ini

Pages never choose tags or TTL values themselves. They call a query function, and that function knows its own cache rules. This one habit prevents most cache bugs later.

Build a Cached Sanity Fetch Helper with Tags and TTL

One helper wraps every request. It forces each query to declare a tag list and a revalidate time, so nothing falls back to a silent default.

ts

// lib/sanity/fetch.ts

import { client } from './client'; // createClient({ useCdn: true, ... })

type Options = {

query: string;

params?: Record<string, unknown>;

tags: string[];

revalidate: number;

};

export function sanityFetch<T>({ query, params = {}, tags, revalidate }: Options) {

return client.fetch<T>(query, params, { next: { revalidate, tags } });

}

⭐ Football Update: jaypateldev/stop hitting the sanity api on every request build smart caching with nextjs isr and webhooks d - Pertandingan Hari Ini ⭐ Football Update: jaypateldev/stop hitting the sanity api on every request build smart caching with nextjs isr and webhooks d - Pertandingan Hari Ini

A query file then stays short and clear:

ts

// lib/sanity/queries.ts

export const getPost = (slug: string) =>

sanityFetch<Post>({

query: postQuery,

params: { slug },

tags: [TAGS.all, TAGS.post(slug)],

revalidate: 3600,

});
⭐ Football Update: jaypateldev/stop hitting the sanity api on every request build smart caching with nextjs isr and webhooks d - Pertandingan Hari Ini ⭐ Football Update: jaypateldev/stop hitting the sanity api on every request build smart caching with nextjs isr and webhooks d - Pertandingan Hari Ini

Choosing Sanity ISR Revalidate Values by Content Type

Because content types are not updated at the same frequency, assign an appropriate time value to each one. Treat the numbers below as a starting point and adjust them after you watch real traffic.

Content Revalidate Tags
Single post 1 hour blog, blog:post:slug
Post listing 30 minutes blog, blog:listing
Categories 24 hours blog:taxonomy
Site settings 24 hours blog:settings
Slugs for sitemap 1 hour blog, blog:slugs

Design Cache Tags for Targeted Sanity Cache Invalidation

Tags are labels on cached responses. A good tag plan lets you clear exactly what changed and keep the rest warm. A bad plan forces you to wipe everything or leave stale pages behind.

Here is the tag map I use for a blog. Each tag answers one question about what a cached response contains:

  • blog marks every blog related response.
  • blog:post: marks one article.
  • blog:listing marks lists and archive pages.
  • blog:taxonomy marks categories and tags.
  • blog:slugs marks sitemap and static params queries.

Put these names in one file so typos cannot split your cache in two:

ts

// lib/cache/tags.ts

export const TAGS = {

all: 'blog',

listing: 'blog:listing',

taxonomy: 'blog:taxonomy',

slugs: 'blog:slugs',

post: (slug: string) => `blog:post:${slug}`,

};

export function tagsFor(p: { _type: string; slug?: string; operation: string }) {

if (p._type === 'category') return [TAGS.taxonomy];

if (p._type !== 'post') return [];

const tags = [TAGS.listing];

if (p.slug) tags.push(TAGS.post(p.slug));

if (p.operation !== 'update') tags.push(TAGS.slugs);

return tags;

}
⭐ Football Update: jaypateldev/stop hitting the sanity api on every request build smart caching with nextjs isr and webhooks d - Pertandingan Hari Ini ⭐ Football Update: jaypateldev/stop hitting the sanity api on every request build smart caching with nextjs isr and webhooks d - Pertandingan Hari Ini

Notice that a simple edit never touches the slug list. A new or deleted post does. This small rule keeps your cache hit rate high.

Configuring Sanity Webhooks to Trigger Next.js Revalidation

Time based refresh alone makes editors wait. A webhook closes that gap. Whenever a document is created, updated, or deleted, Sanity sends a request to your webhook route, which then invalidates the corresponding tags.

Sanity Webhook Projection for a Small Payload

In the Sanity webhook settings, filter by _type in ["post", "category"] and send a small projection. A small payload is faster to send and easier to validate.

{

_id,

_type,

"slug": slug.current,

"operation": delta::operation()

}
⭐ Football Update: jaypateldev/stop hitting the sanity api on every request build smart caching with nextjs isr and webhooks d - Pertandingan Hari Ini ⭐ Football Update: jaypateldev/stop hitting the sanity api on every request build smart caching with nextjs isr and webhooks d - Pertandingan Hari Ini

The delta::operation() function tells you if the change was a create, update, or delete. That detail drives the tag rules from the previous section.

Route Handler with revalidateTag and Signature Check

Anyone who finds a public revalidation URL could trigger cache clears in a loop and push load back to your Sanity project. The parseBody helper from next-sanity checks the signature using your shared secret, so only Sanity can use the route.

ts

// app/api/revalidate/sanity/route.ts

import { revalidateTag } from 'next/cache';

import { NextRequest, NextResponse } from 'next/server';

import { parseBody } from 'next-sanity/webhook';

import { tagsFor } from '@/lib/cache/tags';

import { prisma } from '@/lib/db';

type Payload = { _type: string; slug?: string; operation: string };

export async function POST(req: NextRequest) {

try {

const { isValidSignature, body } = await parseBody<Payload>(

req,

process.env.SANITY_WEBHOOK_SECRET

);

if (!isValidSignature) {

return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });

}

if (!body?._type) {

return NextResponse.json({ error: 'Bad payload' }, { status: 400 });

}

const eventId = req.headers.get('idempotency-key') ?? crypto.randomUUID();

if (await prisma.webhookEvent.findUnique({ where: { id: eventId } })) {

return NextResponse.json({ skipped: true });

}

const tags = tagsFor(body);

tags.forEach((tag) => revalidateTag(tag, 'max'));

await prisma.webhookEvent.create({

data: { id: eventId, type: body._type, slug: body.slug ?? null, operation: body.operation, tags: tags.join(',') },

});

return NextResponse.json({ revalidated: tags });

} catch (err) {

console.error('Sanity revalidation failed', err);

return NextResponse.json({ error: 'Revalidation failed' }, { status: 500 });

}

}
⭐ Football Update: jaypateldev/stop hitting the sanity api on every request build smart caching with nextjs isr and webhooks d - Pertandingan Hari Ini ⭐ Football Update: jaypateldev/stop hitting the sanity api on every request build smart caching with nextjs isr and webhooks d - Pertandingan Hari Ini

One version note. Next.js 16 expects a cache life profile as the second argument to revalidateTag, and 'max' gives stale while revalidate behavior. On Next.js 15, remove that second argument.

Database Integration: Log Webhook Events and Block Duplicates

Sanity can retry a failed delivery, and each delivery carries an idempotency-key header. If you store that key, a retry becomes a harmless no-op instead of a second round of cache clears.

A small table is enough. This Prisma model records what arrived and which tags were cleared:

prisma

model WebhookEvent {

id String @id

type String

slug String?

operation String

tags String

createdAt DateTime @default(now())

}
⭐ Football Update: jaypateldev/stop hitting the sanity api on every request build smart caching with nextjs isr and webhooks d - Pertandingan Hari Ini ⭐ Football Update: jaypateldev/stop hitting the sanity api on every request build smart caching with nextjs isr and webhooks d - Pertandingan Hari Ini

This table also serves as a record for tracking and reviewing previous changes. When an editor says "I published an hour ago and the page is old," you can check whether the event arrived. If it did, you know the problem lies in your tags. If it did not, you know to look at the webhook settings. That saves real debugging time.

Error Handling for Sanity Fetch and Webhook Failures

Plan for failure in both directions. The fetch side and the webhook side break in different ways, and each needs its own response.

On the fetch side, ISR helps you. If a background rebuild throws because Sanity is slow or down, Next.js keeps serving the last good page. So let the error surface in your logs, and do not hide it with an empty fallback that would replace good content with nothing. For pages that must render a first time, wrap the call and return notFound() only when Sanity truly says the document does not exist.

On the webhook side, use clear status codes. Return 401 for a bad signature, 400 for a broken payload, and 500 for an unexpected crash. A 500 matters because it tells Sanity the delivery failed, which lets retries do their job. Never return 200 from inside a catch block just to keep logs quiet.

Last, keep your time values as the backup plan. If the webhook never arrives, the revalidate window still brings fresh data. Webhook for speed, time value for safety.

Production Readiness Checklist for Sanity Caching in Next.js

Before launch, test the full loop on a staging site. Publish a post, watch the webhook attempt in Sanity, check your event table, and confirm the page changes within seconds.

Next.js High Traffic Optimization Steps

These checks keep a busy site stable. Each one removes a common source of surprise load or stale content.

  • Give every query explicit tags and a revalidate value through the shared helper.
  • Keep draft mode on a separate client with a token and no CDN.
  • Store the webhook secret in environment variables and rotate it when staff change.
  • Watch Sanity API usage after launch and compare it with your traffic.
  • Avoid very short revalidate windows, since they create calls the content never needed.

Here is how this plays out in practice. If one popular article receives a thousand visits in a minute, the first request may miss and fill the cache. The other 999 read from the Next.js Data Cache. The Sanity API CDN covers most refills, so the origin sees almost nothing.

Common Mistakes When Caching Sanity Data in Next.js

The first mistake is using only a time value and no tags. Editors then wait for the full window before a fix goes live, which defeats the point of instant publishing.

The second is clearing too much. If every settings change wipes the whole blog tag, you create a burst of Sanity calls for no reason. Match the tag to the change.

The third is trusting the webhook without a secret. An open route is an easy target, so validate the signature every time.

Conclusion

Smart Sanity caching in Next.js is a set of small, clear rules working together. The Next.js Data Cache answers most requests, the Sanity API CDN covers most of the rest, tags keep invalidation precise, and a signed webhook delivers fresh content in seconds. Your revalidate values stay quietly in the background as insurance.

Start with the shared fetch helper, then add the tag file, then the webhook route. Test each step on staging, and you will have a Sanity powered site that stays fast under load and still updates the moment an editor hits publish.

Source : https://jaypateldev.com/blog/sanity-cms-caching-nextjs/

Top comments (1)

⭐ Football Update: jaypateldev/stop hitting the sanity api on every request build smart caching with nextjs isr and webhooks d - Pertandingan Hari Ini
 
posting-dude profile image
Posting Dude •

Keeping tags and TTLs out of the pages and in one lib folder is a good call. Mine are scattered and I honestly can't tell what's cached without curling the headers. On the webhook, if a call fails, is the revalidate time your only safety net, and what value do you usually pick for it?