import { revalidatePath } from 'next/cache'; import { NextRequest, NextResponse } from 'next/server'; /** * 按需重新验证 API 路由 * 当后端内容更新时,通过调用此 API 来手动触发特定页面的重新生成。 * * 调用方式: * POST /api/revalidate * Headers: * Content-Type: application/json * x-revalidate-secret: YOUR_SECRET_TOKEN * Body: * { * "path": "/page-to-revalidate" * } */ export async function POST(request) { // 1. 从请求头中获取密钥 const secret = request.headers.get('x-revalidate-secret'); // 2. 验证密钥 // 为了安全,这个密钥应该存储在环境变量中,并且不能硬编码。 if (secret !== process.env.REVALIDATE_TOKEN) { console.warn('Invalid revalidate token received.'); return NextResponse.json({ message: 'Invalid token' }, { status: 401 }); } // 3. 从请求体中获取并记录需要重新验证的路径 const body = await request.json(); const { path } = body; console.log('Revalidation request body:', body); if (!path) { console.warn('Revalidation request received without a path.'); return NextResponse.json({ message: 'Path is required' }, { status: 400 }); } try { // 4. 调用 Next.js 的 revalidatePath 函数 // 这将清除指定路径的缓存,并在下次请求时重新生成页面。 revalidatePath(path); console.log(`Successfully revalidated path: ${path}`); return NextResponse.json({ revalidated: true, now: Date.now() }); } catch (error) { // 5. 如果发生错误,返回错误信息 console.error(`Error revalidating path: ${path}`, error); return NextResponse.json( { message: 'Error revalidating', error: error.message }, { status: 500 } ); } }