Skip to content

Commit

Permalink
improve: use API to revalidate blogs on publish (#82)
Browse files Browse the repository at this point in the history
* improve: use API to revalidate blogs on publish

Signed-off-by: james-a-morris <[email protected]>

* nit: EOL

* improve: specific page

Signed-off-by: james-a-morris <[email protected]>

---------

Signed-off-by: james-a-morris <[email protected]>
  • Loading branch information
james-a-morris authored Oct 15, 2024
1 parent a860428 commit 7467472
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/app/(routes)/blog/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 1 addition & 0 deletions src/app/_constants/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
26 changes: 26 additions & 0 deletions src/app/api/revalidate/route.ts
Original file line number Diff line number Diff line change
@@ -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() });
}

0 comments on commit 7467472

Please sign in to comment.