Introduction
Incremental Static Regeneration (ISR) in Next.js combines the benefits of static site generation and server-side rendering. It allows you to update static pages after the initial build, providing up-to-date content without rebuilding the entire site.
How does ISR work?
ISR enables you to set a revalidate interval in getStaticProps, determining how often a page is regenerated in the background. If a page is stale when requested, it regenerates while serving the old content, and updates the page for future requests.
Implementing ISR
Step 1. Setup a Next.js Project
Create or use an existing Next.js project.
npx create-next-app isr-example
cd isr-example
Step 2. Create a Page with ISR
Add ISR to a page by setting the revalidate property in getStaticProps:
import React from 'react';
export async function getStaticProps() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await res.json();
return {
props: { posts },
revalidate: 10, // Regenerate every 10 seconds
};
}
const Posts = ({ posts }) => (
<div>
<h1>Posts</h1>
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
export default Posts;
Step 3. Run the Development Server
npm run dev
Visit http://localhost:3000/posts to see ISR in action.
Advanced ISR Features
On-Demand ISR
Trigger ISR manually using an API route.
// pages/api/revalidate.js
export default async function handler(req, res) {
if (req.query.secret !== 'your-secret-token') {
return res.status(401).json({ message: 'Invalid token' });
}
try {
await res.unstable_revalidate('/posts');
return res.json({ revalidated: true });
} catch {
return res.status(500).json({ message: 'Error revalidating' });
}
}
Trigger revalidation with.
curl -X POST https://your-site.com/api/revalidate?secret=your-secret-token
Fallback Pages
Use ISR with dynamic routes and fallback options.
// pages/posts/[id].js
export async function getStaticPaths() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await res.json();
const paths = posts.map(post => ({ params: { id: post.id.toString() } }));
return { paths, fallback: 'blocking' };
}
export async function getStaticProps({ params }) {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${params.id}`);
const post = await res.json();
return {
props: { post },
revalidate: 10,
};
}
const Post = ({ post }) => (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
export default Post;
Summary
ISR in Next.js provides a way to combine static and dynamic rendering benefits. By using ISR, you can keep your site fast and SEO-friendly while ensuring content updates without full rebuilds.