typescriptadvanced

On-Demand ISR Revalidation

Trigger incremental static regeneration via API route with secret token validation for instant cache purge.

typescript
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.