77 lines
2.0 KiB
TypeScript
77 lines
2.0 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { revalidateTag, revalidatePath } from 'next/cache';
|
|
|
|
export async function GET(request: NextRequest) {
|
|
return handleRevalidate(request);
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
return handleRevalidate(request);
|
|
}
|
|
|
|
async function handleRevalidate(request: NextRequest) {
|
|
const { searchParams } = new URL(request.url);
|
|
let secret = searchParams.get('secret') || request.headers.get('x-revalidate-secret');
|
|
let tag = searchParams.get('tag');
|
|
let path = searchParams.get('path');
|
|
|
|
// Check auth header if bearer token provided
|
|
const authHeader = request.headers.get('authorization');
|
|
if (authHeader && authHeader.startsWith('Bearer ')) {
|
|
secret = authHeader.substring(7);
|
|
}
|
|
|
|
if (request.method === 'POST') {
|
|
try {
|
|
const body = await request.json().catch(() => ({}));
|
|
if (body && typeof body === 'object') {
|
|
if (body.secret) secret = body.secret;
|
|
if (body.tag) tag = body.tag;
|
|
if (body.path) path = body.path;
|
|
}
|
|
} catch {
|
|
// Ignore body read error
|
|
}
|
|
}
|
|
|
|
const expectedSecret = process.env.REVALIDATION_SECRET;
|
|
if (!expectedSecret) {
|
|
return NextResponse.json(
|
|
{ success: false, message: 'Revalidation service is not configured' },
|
|
{ status: 503 }
|
|
);
|
|
}
|
|
|
|
if (!secret || secret !== expectedSecret) {
|
|
return NextResponse.json(
|
|
{ success: false, message: 'Invalid revalidation secret token' },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
if (!tag && !path) {
|
|
return NextResponse.json(
|
|
{ success: false, message: 'Missing tag or path parameter for cache revalidation' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const revalidated: { tag?: string; path?: string } = {};
|
|
|
|
if (tag) {
|
|
revalidateTag(tag, 'default');
|
|
revalidated.tag = tag;
|
|
}
|
|
|
|
if (path) {
|
|
revalidatePath(path);
|
|
revalidated.path = path;
|
|
}
|
|
|
|
return NextResponse.json({
|
|
revalidated: true,
|
|
...revalidated,
|
|
now: Date.now(),
|
|
});
|
|
}
|