Incremental Static Regeneration (ISR) is a powerful feature in frameworks like Next.js that allows you to create or update static pages after the build time. This is particularly useful when dealing with dynamic routes, where the content can change frequently, such as blog posts or product pages. Combining ISR with dynamic routes enables you to serve static pages that can be regenerated on-demand, ensuring that users always see the most up-to-date content without sacrificing performance.
To effectively combine ISR with dynamic routes, you need to understand how to set up your pages and configure the regeneration process. Below, I will outline the steps involved, best practices, and common pitfalls to avoid.
In Next.js, dynamic routes are created using square brackets in the file name. For example, to create a dynamic route for blog posts, you would create a file named [slug].js inside the pages/posts directory.
import { useRouter } from 'next/router';
const Post = ({ post }) => {
return (
{post.title}
{post.content}
);
};
export async function getStaticPaths() {
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
const paths = posts.map(post => ({
params: { slug: post.slug },
}));
return { paths, fallback: 'blocking' };
}
export async function getStaticProps({ params }) {
const res = await fetch(`https://api.example.com/posts/${params.slug}`);
const post = await res.json();
return {
props: { post },
revalidate: 10, // Regenerate the page every 10 seconds
};
}
export default Post;
getStaticPaths, consider the fallback option. Setting it to 'blocking' ensures that users will see the updated content without a loading state.By following these guidelines, you can effectively combine ISR with dynamic routes in your Next.js applications, providing a seamless user experience while keeping your content fresh and performant.