From 7467472a0e16be9b3388931d9648fcca0418d5e5 Mon Sep 17 00:00:00 2001 From: "James Morris, MS" <96435344+james-a-morris@users.noreply.github.com> Date: Tue, 15 Oct 2024 13:58:04 -0400 Subject: [PATCH] improve: use API to revalidate blogs on publish (#82) * improve: use API to revalidate blogs on publish Signed-off-by: james-a-morris * nit: EOL * improve: specific page Signed-off-by: james-a-morris --------- Signed-off-by: james-a-morris --- src/app/(routes)/blog/[slug]/page.tsx | 3 +++ src/app/_constants/environment.ts | 1 + src/app/api/revalidate/route.ts | 26 ++++++++++++++++++++++++++ 3 files changed, 30 insertions(+) create mode 100644 src/app/api/revalidate/route.ts diff --git a/src/app/(routes)/blog/[slug]/page.tsx b/src/app/(routes)/blog/[slug]/page.tsx index 8ea6e75..bce24ab 100644 --- a/src/app/(routes)/blog/[slug]/page.tsx +++ b/src/app/(routes)/blog/[slug]/page.tsx @@ -132,3 +132,6 @@ export default async function SpecificBlogPage({ params }: SpecificBlogPageProps ); } + +// Add revalidate for ISR at the page level +export const revalidate = 60; // revalidate every 60 seconds diff --git a/src/app/_constants/environment.ts b/src/app/_constants/environment.ts index cf9cc09..c5f8c95 100644 --- a/src/app/_constants/environment.ts +++ b/src/app/_constants/environment.ts @@ -9,3 +9,4 @@ export const GOOGLE_ANALYTICS_TAG_ID = process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_ // Server side environment variables export const CONTENTFUL_SPACE_ID = process.env.CONTENTFUL_SPACE_ID; export const CONTENTFUL_ACCESS_TOKEN = process.env.CONTENTFUL_ACCESS_TOKEN; +export const CONTENTFUL_REVALIDATE_SECRET = process.env.CONTENTFUL_REVALIDATE_SECRET; diff --git a/src/app/api/revalidate/route.ts b/src/app/api/revalidate/route.ts new file mode 100644 index 0000000..2fc3f41 --- /dev/null +++ b/src/app/api/revalidate/route.ts @@ -0,0 +1,26 @@ +import { NextRequest, NextResponse } from "next/server"; +import { revalidatePath } from "next/cache"; +import { CONTENTFUL_REVALIDATE_SECRET } from "@/app/_constants"; + +export async function POST(request: NextRequest) { + const requestHeaders = new Headers(request.headers); + const secret = requestHeaders.get("x-vercel-reval-key"); + + if (secret !== CONTENTFUL_REVALIDATE_SECRET) { + return NextResponse.json({ message: "Invalid secret" }, { status: 401 }); + } + + const body = await request.json(); + const slug = body?.fields?.slug?.["en-US"]; + + if (typeof slug !== "string") { + return NextResponse.json({ message: "Invalid request body" }, { status: 400 }); + } + + // Revalidate blog post and all related pages + revalidatePath(`/blog/${slug}`); + // Revalidate home page + revalidatePath("/blog"); + + return NextResponse.json({ revalidated: true, slug, now: Date.now() }); +}