On-demand revalidation lets your Next.js app update specific pages without rebuilding the whole site. It keeps content fresh and fast.
On-demand revalidation in NextJS
import { NextApiRequest, NextApiResponse } from 'next'; export default async function handler(req: NextApiRequest, res: NextApiResponse) { // Check secret token for security if (req.query.secret !== process.env.MY_SECRET_TOKEN) { return res.status(401).json({ message: 'Invalid token' }); } try { // Revalidate the page at the given path await res.revalidate('/path-to-revalidate'); return res.json({ revalidated: true }); } catch (err) { return res.status(500).send('Error revalidating'); } }
You create an API route that calls res.revalidate(path) to refresh a page.
Use a secret token to protect the API route from unauthorized calls.
export default async function handler(req, res) { if (req.query.secret !== process.env.MY_SECRET) { return res.status(401).json({ message: 'Unauthorized' }); } await res.revalidate('/blog/post-1'); return res.json({ revalidated: true }); }
export default async function handler(req, res) { const slug = req.query.slug; if (!slug || req.query.secret !== process.env.MY_SECRET) { return res.status(401).json({ message: 'Unauthorized' }); } await res.revalidate(`/products/${slug}`); return res.json({ revalidated: true }); }
This API route revalidates the home page when called with the correct secret token. It helps update the home page content without a full rebuild.
import { NextApiRequest, NextApiResponse } from 'next'; export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.query.secret !== process.env.MY_SECRET_TOKEN) { return res.status(401).json({ message: 'Invalid token' }); } try { await res.revalidate('/'); return res.json({ revalidated: true }); } catch (err) { return res.status(500).send('Error revalidating'); } }
Always protect your revalidation API route with a secret token to avoid misuse.
On-demand revalidation works only with pages using getStaticProps and revalidate set.
Use this method to keep static pages fresh without slowing down your site.
On-demand revalidation updates specific pages instantly without rebuilding the whole site.
It uses an API route that calls res.revalidate(path) with a secret token for security.
This keeps your static pages fresh and fast for users.