On-Demand ISR Revalidation
Trigger incremental static regeneration via API route with secret token validation for instant cache purge.
import { NextRequest, NextResponse } from 'next/server';
import { revalidatePath, revalidateTag } from 'next/cache';
export async function POST(request: NextRequest) {
const secret = request.headers.get('x-revalidation-secret');
if (secret !== process.env.REVALIDATION_SECRET) {
return NextResponse.json({ error: 'Invalid secret' }, { status: 401 });
}
try {
const body = await request.json();
const { type, value } = body as { type: 'path' | 'tag'; value: string };
if (type === 'path') {
revalidatePath(value);
} else if (type === 'tag') {
revalidateTag(value);
} else {
return NextResponse.json({ error: 'Invalid type' }, { status: 400 });
}
return NextResponse.json({
revalidated: true,
type,
value,
timestamp: Date.now(),
});
} catch {
return NextResponse.json(
{ error: 'Failed to revalidate' },
{ status: 500 }
);
}
}
// Usage (from CMS webhook or admin panel):
// curl -X POST https://example.com/api/revalidate \
// -H 'x-revalidation-secret: my-secret' \
// -H 'Content-Type: application/json' \
// -d '{"type": "path", "value": "/blog/my-post"}'Use Cases
- CMS content updates
- Admin panel publish actions
- Webhook-triggered cache busting
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
Authentication Middleware Guard
Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.
Dynamic OG Image Generation
Generate Open Graph images on-the-fly using Next.js ImageResponse with custom fonts and dynamic content.