Hybrid Rendering with On-Demand Revalidation
Combine `getStaticProps`, `getServerSideProps`, and `getStaticPaths` with on-demand revalidation using an API route to trigger re-generation of static pages.
// 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 {
// Path to revalidate
const pathToRevalidate = req.query.path;
// Trigger a revalidation (rebuild) of the page
await res.unstable_revalidate(pathToRevalidate);
return res.json({ revalidated: true });
} catch (err) {
// If there was an error, return it
return res.status(500).send('Error revalidating');
}
}
API route to trigger on-demand revalidation of a specified path. It checks a secret token for security and uses unstable_revalidate to re-generate the page.
// pages/[id].js
export async function getStaticPaths() {
// Here you'd fetch an array of possible paths
const paths = ['path1', 'path2'];
return {
paths: paths.map(id => ({ params: { id } })),
fallback: 'blocking' // 'blocking' or true
};
}
export async function getStaticProps(context) {
const { params } = context;
// Here you'd fetch the data for the page
return { props: { /* Your data */ }, revalidate: 60 };
}
// Info about component using the data omitted for brevity
Static generation functions for a dynamically routed page. It defines possible paths and includes `revalidate` to automate re-generation at most every 60 seconds.
// pages/_app.js
export function reportWebVitals(metric) {
// Check which metric to report and send to an analytics endpoint
// Example: measuring the Largest Contentful Paint (LCP)
if (metric.name === 'LCP') {
// Use `navigator.sendBeacon` or another method to report the metric
// sendToAnalytics(metric);
}
}
// Component definition omitted for brevity
Optional web vitals reporting function to optionally measure performance for static generation. Can be used alongside getStaticProps to monitor and trigger revalidation.