Sanity and Next.js Automatic Static Optimization
Ah, the classic "why isn't my static site updating?" conundrum! 🐅
The issue you're experiencing is because Next.js's Automatic Static Optimization generates pages at build time, and those pages stay static until you explicitly tell Next.js to regenerate them. When you update content in Sanity, your Next.js site has no idea that anything changed—it's still serving those old static pages.
Here are your main options to fix this:
1. Incremental Static Regeneration (ISR) - Time-based
The simplest solution is to add a revalidate property to your data fetching. This tells Next.js to regenerate the page in the background after a certain number of seconds:
export async function getStaticProps() {
const data = await sanityClient.fetch(query)
return {
props: { data },
revalidate: 60 // Regenerate page every 60 seconds if there's a request
}
}The catch? If you fix a typo, you might have to wait up to 60 seconds (or whatever interval you set) before it appears. Learn more about ISR.
2. On-Demand Revalidation with revalidateTag - Event-based (Recommended!)
This is the modern, surgical approach. You tag your queries, then trigger revalidation when content actually changes:
Step 1: Tag your queries:
const posts = await sanityFetch({
query: POSTS_QUERY,
tags: ['post', 'author', 'category'],
})Step 2: Create an API route to handle revalidation:
// app/api/revalidate/route.ts
import { revalidateTag } from 'next/cache'
import { type NextRequest, NextResponse } from 'next/server'
export async function POST(req: NextRequest) {
const { tags } = await req.json()
for (const tag of tags) {
revalidateTag(tag)
}
return NextResponse.json({ revalidated: true })
}Step 3: Set up a webhook in Sanity or use Sanity Functions to call this endpoint when content changes.
With Sanity Functions, you could even skip the webhook entirely and handle revalidation directly within Sanity's infrastructure—it's the modern, recommended approach for this kind of automation.
3. Pro tip: Disable Sanity CDN during revalidation
If you're using ISR, set useCdn: false in your Sanity client config. The Sanity CDN and Next.js ISR can work at cross-purposes, potentially serving you stale data even after revalidation triggers.
const client = createClient({
// ... other config
useCdn: false, // Important for ISR!
})The tag-based revalidation approach is generally the best solution for production sites—you get instant updates when content changes without unnecessary regenerations. Check out Sanity's course on controlling cached content in Next.js for a deep dive!
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.