Issue with slug paths not updating in Next.js application due to caching.
This sounds like a classic Next.js caching issue! When you update content in Sanity, your Next.js app doesn't automatically know about the change because it's serving cached data. Here's what's likely happening and how to fix it:
The Problem
Next.js aggressively caches data to improve performance. When you update a slug in Sanity and publish it, your Next.js application continues serving the old cached version until that cache is invalidated.
Solutions
1. Set up On-Demand Revalidation (Recommended)
The best approach is to use Next.js's revalidateTag function combined with Sanity webhooks or Functions:
Step 1: Tag your queries in Next.js:
const products = await sanityFetch({
query: PRODUCTS_QUERY,
tags: ['product'], // Tag this query
})
// For individual product pages:
const product = await sanityFetch({
query: PRODUCT_QUERY,
params: { slug },
tags: [`product:${slug}`, 'product'],
})Step 2: Create an API route to handle revalidation:
// app/api/revalidate/route.ts
import { revalidateTag } from 'next/cache'
import { 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 Sanity webhook pointing to your revalidation endpoint (e.g., https://yoursite.com/api/revalidate), or better yet, use Sanity Functions for a more integrated approach that doesn't require external hosting.
2. Use Time-Based Revalidation (ISR)
For a simpler but less efficient approach, add time-based revalidation to your fetch calls:
const products = await sanityFetch({
query: PRODUCTS_QUERY,
revalidate: 60, // Revalidate every 60 seconds
})Note: You can't use both tags and time-based revalidation together - they're mutually exclusive.
3. Use the Live Content API
If you want real-time updates without managing cache manually, consider using the Live Content API which handles fetching, caching, and invalidation automatically.
Quick Fix for Testing
During development, you can force a fresh fetch by:
- Hard refreshing your browser (Cmd/Ctrl + Shift + R)
- Restarting your Next.js dev server
- Clearing your
.nextcache folder
The on-demand revalidation approach is definitely the way to go for production - it gives you instant updates when content changes without sacrificing performance!
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.