31 lines
1.2 KiB
TypeScript
31 lines
1.2 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { revalidateTag } from 'next/cache';
|
|
|
|
// Validate tag pattern matching allowlist: products, categories, layout, or product-<slug>
|
|
const ALLOWED_TAG_REGEX = /^(products|categories|layout|brands|product-[a-zA-Z0-9_-]+)$/;
|
|
|
|
export async function POST(req: NextRequest) {
|
|
const authHeader = req.headers.get('authorization');
|
|
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
|
return NextResponse.json({ message: 'Missing or malformed Authorization header' }, { status: 401 });
|
|
}
|
|
|
|
const token = authHeader.substring(7);
|
|
if (token !== process.env.REVALIDATION_TOKEN) {
|
|
return NextResponse.json({ message: 'Unauthorized access token' }, { status: 401 });
|
|
}
|
|
|
|
try {
|
|
const body = await req.json();
|
|
const tag = body?.tag;
|
|
|
|
if (!tag || !ALLOWED_TAG_REGEX.test(tag)) {
|
|
return NextResponse.json({ message: 'Invalid or restricted revalidation tag' }, { status: 400 });
|
|
}
|
|
|
|
revalidateTag(tag);
|
|
return NextResponse.json({ revalidated: true, tag, timestamp: Date.now() });
|
|
} catch (e: any) {
|
|
return NextResponse.json({ message: 'Malformed JSON payload body or internal revalidation error' }, { status: 400 });
|
|
}
|
|
}
|