Skip to content

Instantly share code, notes, and snippets.

@jeromecovington
Created February 8, 2023 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeromecovington/515c6246b634ab8add5fd2e945cf0d04 to your computer and use it in GitHub Desktop.
Save jeromecovington/515c6246b634ab8add5fd2e945cf0d04 to your computer and use it in GitHub Desktop.
NextJS on-demand revalidation endpoint
import { NextApiRequest, NextApiResponse } from "next";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (
!req.query.revalidate_token ||
!process.env.REVALIDATE_TOKEN ||
req.query.revalidate_token !== process.env.REVALIDATE_TOKEN
) {
return res.status(401).json({ message: "Invalid token" });
}
if (!req.query.revalidate_path) {
return res.status(422).json({ message: "No revalidate path provided" });
}
try {
// This should be the actual path e.g. "/my-category/my-story"
await res.revalidate(req.query.revalidate_path as string);
return res.json({ revalidated: true });
} catch (err) {
// If there was an error, the last successfully generated page will show.
return res.status(500).send("Error revalidating");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment