Performance: On-demand revalidation
On-demand revalidation affects how quickly updated content appears without rebuilding the entire site, impacting page load speed and freshness.
Jump into concepts and practice - no test required
import { NextApiRequest, NextApiResponse } from 'next'; export default async function handler(req, res) { // Trigger revalidation for specific path await res.revalidate('/path-to-update'); res.json({ revalidated: true }); } // Only updated pages rebuild on demand
export async function getStaticProps() { // fetch data return { props: { data }, revalidate: 60 }; } // Full site rebuild triggered on every change or long revalidate interval
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Full static rebuild on every change | N/A (server-side) | N/A | Blocks LCP until rebuild completes | [X] Bad |
| On-demand revalidation for specific pages | N/A (server-side) | N/A | Minimal impact on LCP, fast update | [OK] Good |
res.revalidate(path) to trigger revalidation of a page.export default async function handler(req, res) {
if (req.method === 'POST' && req.query.secret === process.env.MY_SECRET) {
await res.revalidate('/blog/post-1')
return res.json({ revalidated: true })
}
return res.status(401).json({ message: 'Invalid token' })
}res.revalidate('/blog/post-1') to update that page only.export default async function handler(req, res) {
if (req.method === 'GET' && req.query.secret === process.env.SECRET) {
await res.revalidate('/home')
res.json({ revalidated: true })
} else {
res.status(401).json({ message: 'Unauthorized' })
}
}res.revalidate() and sending JSON, the function should return to avoid continuing execution.res.json() but does not return, which can cause errors or multiple responses.res.revalidate() method accepts a single path string and returns a promise.await res.revalidate() separately for each path before sending response.