Developing ISR (Incremental Static Regeneration) for a website
Incremental Static Regeneration — SSG with the ability to update individual pages without full site rebuild. A page is generated once, cached, and revalidated in the background on the next request after cache expires. Users always get instant responses from cache, and content freshness is guaranteed by TTL.
ISR fills the gap between SSG (instant delivery, stale content) and SSR (fresh content, server latency on every request).
How ISR works
Classic model (Stale-While-Revalidate at page level):
- First request to a page — server render, HTML cached
- Repeated requests within TTL — cache delivery, response under 10ms
- Request after TTL expires — deliver stale cache (user doesn't wait), start background revalidation
- Next request — fresh HTML from updated cache
Result: TTFB like static sites, content freshness like SSR.
Implementation in Next.js App Router
// app/products/[id]/page.tsx
interface Props {
params: { id: string };
}
async function getProduct(id: string): Promise<Product | null> {
const res = await fetch(`https://api.example.com/products/${id}`, {
next: {
revalidate: 300, // Revalidate no more than once per 5 minutes
tags: [`product-${id}`], // Tag for on-demand revalidation
},
});
if (!res.ok) return null;
return res.json();
}
export default async function ProductPage({ params }: Props) {
const product = await getProduct(params.id);
if (!product) notFound();
return <ProductView product={product} />;
}
// Pre-generate popular pages at build time
export async function generateStaticParams() {
const popularProducts = await fetch('https://api.example.com/products?popular=true&limit=100')
.then(r => r.json());
return popularProducts.map(({ id }: { id: string }) => ({ id }));
}
Pages from generateStaticParams are generated at build time. All others are on-demand and then revalidated by TTL.
On-Demand Revalidation — immediate update
TTL cache doesn't work when you need to update immediately after CMS changes. Use on-demand revalidation via API:
// app/api/revalidate/route.ts
import { revalidateTag, revalidatePath } from 'next/cache';
import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
const secret = request.headers.get('x-revalidate-secret');
if (secret !== process.env.REVALIDATE_SECRET) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { tag, path } = await request.json();
if (tag) {
revalidateTag(tag); // Invalidate everything with this tag
}
if (path) {
revalidatePath(path); // Invalidate specific path
}
return NextResponse.json({ revalidated: true, at: new Date().toISOString() });
}
CMS webhook calls this endpoint on publish:
# Example Contentful webhook request
curl -X POST https://example.com/api/revalidate \
-H "x-revalidate-secret: ${REVALIDATE_SECRET}" \
-H "Content-Type: application/json" \
-d '{"tag": "product-42"}'
Implementation in Nuxt 3
<!-- pages/products/[id].vue -->
<script setup lang="ts">
const route = useRoute();
// Nuxt cachedFetch with TTL
const { data: product } = await useFetch<Product>(
`/api/products/${route.params.id}`,
{
key: `product-${route.params.id}`,
getCachedData: (key, nuxtApp) => nuxtApp.payload.data[key],
}
);
// server/api/products/[id].ts uses cache() from nitro
</script>
// server/api/products/[id].ts
import { defineEventHandler, getRouterParam } from 'h3';
export default cachedEventHandler(
async (event) => {
const id = getRouterParam(event, 'id');
return await $fetch(`https://api.example.com/products/${id}`);
},
{
maxAge: 300,
staleMaxAge: 3600,
name: 'product',
getKey: (event) => `product-${getRouterParam(event, 'id')}`,
}
);
Caching strategies
ISR allows setting different TTLs for different page types:
| Page type | TTL | Logic |
|---|---|---|
| Home page | 60 sec | Updates frequently |
| Category page | 300 sec | Changes when products added |
| Product page | 3600 sec | Stable data, price separate query |
| Blog post | 86400 sec | Rarely edited |
| Documentation | On-demand only | Only on publish |
Cache storage for distributed deployment
Vercel has built-in edge cache. For self-hosted Next.js need external cache:
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
cacheHandler: process.env.NODE_ENV === 'production'
? require.resolve('./cache-handler.js')
: undefined,
cacheMaxMemorySize: 0, // Disable in-memory cache with external handler
};
// cache-handler.js — Redis backend
const redis = require('ioredis');
const client = new redis(process.env.REDIS_URL);
module.exports = class CacheHandler {
async get(key) {
const data = await client.get(key);
return data ? JSON.parse(data) : null;
}
async set(key, data, ctx) {
const ttl = ctx.revalidate || 3600;
await client.setex(key, ttl, JSON.stringify({ value: data, lastModified: Date.now() }));
}
async revalidateTag(tag) {
// Scan and delete keys with tag
const keys = await client.smembers(`tag:${tag}`);
if (keys.length) await client.del(...keys);
await client.del(`tag:${tag}`);
}
};
Fallback strategies for new pages
For routes not generated at build time, three behavior options:
// Next.js: dynamicParams controls behavior
export const dynamicParams = true; // Generate on-demand (default)
// export const dynamicParams = false; // 404 for ungenerated paths
// Nuxt: routeRules in nuxt.config.ts
export default defineNuxtConfig({
routeRules: {
'/products/**': { isr: 300 }, // ISR with 5-minute TTL
'/blog/**': { isr: true }, // ISR on-demand only
'/dashboard/**': { ssr: true }, // Pure SSR without cache
'/static/**': { prerender: true }, // SSG only
},
});
Monitoring and debugging
Track in production:
- Cache HIT rate — ratio of cached responses to revalidations
- Revalidation duration — background regeneration time (shouldn't exceed TTL)
- Stale responses — count of responses with stale content
// middleware.ts — cache status logging
import { NextResponse, type NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const response = NextResponse.next();
response.headers.set('x-cache-time', new Date().toISOString());
return response;
}
Implementation timeline
- Week 1–2: stack selection, basic SSG/SSR structure, TTL strategies by page type
- Week 3: on-demand revalidation, CMS webhook integration
- Week 4: Redis cache handler for self-hosted, cache hit rate monitoring
- Week 5: load testing, fallback page optimization, content team documentation
- Week 6: deployment, CI/CD setup with cache warming after build







