Files
canina/frontend/application/app/api/revalidate/route.ts
T
devops ff6f04fe46
Deploy Canina / deploy (push) Successful in 2m35s
fix(cache): revalidate storefront after admin mutations
2026-10-18 19:31:46 +00:00

53 lines
2.2 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 tags: unknown[] = searchParams.getAll('tag');
let paths: unknown[] = searchParams.getAll('path');
const authHeader = request.headers.get('authorization');
if (authHeader?.startsWith('Bearer ')) secret = authHeader.substring(7);
if (request.method === 'POST') {
const body = await request.json().catch(() => ({}));
if (body && typeof body === 'object') {
if (body.secret) secret = body.secret;
if (body.tag) tags = [body.tag];
if (Array.isArray(body.tags)) tags = body.tags;
if (body.path) paths = [body.path];
if (Array.isArray(body.paths)) paths = body.paths;
}
}
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 });
}
const cleanTags = [...new Set(tags.filter((value): value is string => typeof value === 'string' && value.length > 0))];
const cleanPaths = [...new Set(paths.filter((value): value is string => typeof value === 'string' && value.startsWith('/')))];
if (!cleanTags.length && !cleanPaths.length) {
return NextResponse.json({ success: false, message: 'Missing tag or path parameter for cache revalidation' }, { status: 400 });
}
for (const tag of cleanTags) revalidateTag(tag, 'default');
for (const path of cleanPaths) {
try { revalidatePath(path, 'page'); } catch { revalidatePath(path); }
}
return NextResponse.json({ revalidated: true, tags: cleanTags, paths: cleanPaths, now: Date.now() });
}