Incremental Static Regeneration (ISR) is a feature introduced by Next.js that allows you to statically generate pages at build time but also update them periodically without needing to rebuild the entire site. This hybrid approach between static generation and server-side rendering provides the best of both worlds, offering fast page loads and up-to-date content.
In traditional static site generation (SSG), pages are generated once during the build process and remain unchanged until the next build. While this results in excellent performance, it can lead to outdated content if the data changes frequently. ISR addresses this issue by allowing you to regenerate specific pages at a defined interval, ensuring that your users always see the most recent information.
ISR uses the generateStaticParams function and the revalidate option. When you set revalidate, Next.js will automatically update the page in the background at the specified interval. This means that subsequent requests to the page will fetch fresh data, and the updated content will be served to users.
To enable ISR, follow these steps:
generateStaticParams to fetch initial data.revalidate option in your route configuration.Here's an example of how to set up ISR for a blog post page using the App Router:
// app/posts/[id]/page.js
import { notFound } from 'next/navigation';
export async function generateStaticParams() {
// Fetch all posts IDs
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
// Generate paths for each post
return posts.map((post) => ({
id: post.id.toString(),
}));
}
export default async function Post({ params }) {
const { id } = params;
const res = await fetch(`https://api.example.com/posts/${id}`, {
next: { revalidate: 10 }, // Revalidate every 10 seconds
});
if (!res.ok) {
notFound();
}
const post = await res.json();
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
);
}
id.revalidate option is set to 10 seconds, meaning the page will be regenerated every 10 seconds.revalidate interval should balance between performance and freshness. A shorter interval ensures more up-to-date content but may increase server load.ISR is particularly useful for applications where content changes frequently but doesn't require real-time updates. Some examples include:
Incremental Static Regeneration is a powerful feature in Next.js that allows you to serve static pages with dynamic content. By setting the revalidate option, you can ensure that your users always see the most recent information without compromising performance. With careful implementation and monitoring, ISR can significantly enhance the user experience of your application.
By following the guidelines and best practices outlined in this tutorial, you'll be well-equipped to implement ISR in your Next.js projects and take advantage of its benefits.