Skip to content

Instantly share code, notes, and snippets.

@pvaladez
Created August 24, 2024 21:32
Show Gist options
  • Save pvaladez/3f2ef82f9cd7bf02a2ac7c989659cb3d to your computer and use it in GitHub Desktop.
Save pvaladez/3f2ef82f9cd7bf02a2ac7c989659cb3d to your computer and use it in GitHub Desktop.

Revisions

  1. pvaladez revised this gist Aug 24, 2024. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions route.ts
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,5 @@
    // app/api/revalidate/route.ts

    import crypto from 'crypto';
    import { revalidatePath } from 'next/cache';
    import type { NextRequest } from 'next/server';
  2. pvaladez revised this gist Aug 24, 2024. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions route.ts
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,4 @@
    // app/api/revalidate/route.ts
    import crypto from 'crypto';
    import { revalidatePath } from 'next/cache';
    import type { NextRequest } from 'next/server';
  3. pvaladez created this gist Aug 24, 2024.
    36 changes: 36 additions & 0 deletions route.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    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 });
    }
    }