Next.js
Beginner
1 min read
Incremental Static Regeneration (ISR) Deep Dive
Example
// app/products/page.tsx — ISR with on-demand revalidation
// Cache this page and regenerate at most every 10 minutes
export const revalidate = 600;
async function getProducts() {
const res = await fetch('https://api.example.com/products', {
next: {
revalidate: 600,
tags: ['products-list'],
},
});
return res.json();
}
export default async function ProductsPage() {
const products = await getProducts();
return (
<ul>
{products.map((p: { id: string; name: string; price: number }) => (
<li key={p.id}>
{p.name} — ${p.price}
</li>
))}
</ul>
);
}
// app/api/webhooks/cms/route.ts — on-demand revalidation webhook
import { revalidateTag } from 'next/cache';
import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
const secret = request.headers.get('x-webhook-secret');
if (secret !== process.env.WEBHOOK_SECRET) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const payload = await request.json();
// CMS sends the model name; invalidate matching tag
if (payload.model === 'product') {
revalidateTag('products-list');
}
return NextResponse.json({ revalidated: true, at: new Date().toISOString() });
}