Created
February 8, 2023 13:48
-
-
Save jeromecovington/515c6246b634ab8add5fd2e945cf0d04 to your computer and use it in GitHub Desktop.
NextJS on-demand revalidation endpoint
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
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