Created
August 24, 2024 21:32
-
-
Save pvaladez/3f2ef82f9cd7bf02a2ac7c989659cb3d to your computer and use it in GitHub Desktop.
Catalyst Revalidate API Route Handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // app/api/revalidate/route.ts | |
| import crypto from 'crypto'; | |
| import { revalidatePath } from 'next/cache'; | |
| import type { NextRequest } from 'next/server'; | |
| import { NextResponse } from 'next/server'; | |
| export const dynamic = 'force-dynamic'; | |
| export async function GET(request: NextRequest) { | |
| try { | |
| const slug = request.nextUrl.searchParams.get('slug'); | |
| const secret = request.nextUrl.searchParams.get('secret'); | |
| if ( | |
| !secret || | |
| !crypto.timingSafeEqual( | |
| Buffer.from(secret, 'utf8'), | |
| Buffer.from(process.env.NEXT_PRIVATE_REVALIDATION_KEY || '', 'utf8'), | |
| ) || | |
| typeof slug !== 'string' | |
| ) { | |
| // Do not indicate that the revalidation key is incorrect in the response | |
| // This will protect this API route from being exploited | |
| return new Response('Invalid request', { status: 400 }); | |
| } | |
| if (typeof slug === 'string') { | |
| revalidatePath(`/${slug}`, 'layout'); | |
| return NextResponse.json({ revalidated: true, now: Date.now() }); | |
| } | |
| return NextResponse.json({ revalidated: false, now: Date.now() }); | |
| } catch (error: unknown) { | |
| return NextResponse.json({ revalidated: false, now: Date.now(), error }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment