Next.js: On-demand ISR

Next.js: On-demand ISR

Next.js allows for static pages to be updated without a full build to be run. This is achieved via incremental static regeneration (ISR), however, a limitation of ISR is that it revalidates the cache on a set interval.
// pages/myPage.js

export async function getStaticProps(context, params) {
	props: {
		data: // some data
	},
	revalidate: 60 // revalidate every 60 seconds
}
 
// pages/api/revalidate.js

export default async function handler(req, res) {
  // Check for secret to confirm this is a valid request
  if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
    return res.status(401).json({ message: "Invalid token" });
  }

  try {
    await res.unstable_revalidate(`/${req.query.path}`);
    return res.json({ revalidated: true, path: req.query.path });
  } catch (err) {
    // If there was an error, Next.js will continue
    // to show the last successfully generated page
    return res.status(500).send("Error revalidating");
  }
}