Next.js › On-Demand Revalidation Strategies
How would you build a webhook endpoint that automatically revalidates your site whenever content changes in an external content management system?
AdvancedAnswer
You create a route handler that receives a webhook notification from your CMS whenever content is published or updated, verify the request is legitimate using a shared secret, and then call revalidatePath or revalidateTag for the affected content, keeping your site automatically synchronized with your CMS without any manual steps.
// app/api/revalidate/route.js
import { revalidateTag } from 'next/cache';
export async function POST(request) {
const secret = request.headers.get('x-webhook-secret');
if (secret !== process.env.WEBHOOK_SECRET) {
return new Response('Unauthorized', { status: 401 });
}
const { tag } = await request.json();
revalidateTag(tag);
return Response.json({ revalidated: true });
}Real-world example A marketing website automatically refreshes its cached pages the moment an editor publishes new content in their headless CMS, thanks to a webhook that triggers revalidation without any manual redeployment.