Table of Contents
- Introduction
- What is
generateStaticParams
in Next.js? - What is
revalidate
in Next.js? - How
generateStaticParams
andrevalidate
Work Together - Dynamic Pages with
generateStaticParams
andrevalidate
- Best Practices for Dynamic Pages Using
generateStaticParams
andrevalidate
- Real-World Example: Building a Dynamic Product Page
- Conclusion
1. Introduction
Next.js provides a flexible approach to generating static pages with dynamic parameters using generateStaticParams
and revalidate
. These features are especially useful for building dynamic pages where you need to generate pages with parameters that change frequently but don’t necessarily need to be rendered on every request.
In this module, we’ll explore how to use generateStaticParams
to pre-generate pages with dynamic parameters and how revalidate
allows you to refresh those pages at specific intervals without needing a full rebuild.
2. What is generateStaticParams
in Next.js?
In Next.js 14+, generateStaticParams
is a function used for dynamically generating paths for static pages based on parameters. This function allows you to pre-render pages that depend on dynamic parameters, such as blog posts or product pages, at build time.
Unlike traditional static generation methods (like getStaticPaths
), generateStaticParams
gives you more control over dynamically generating paths and can be used in tandem with static generation strategies to build dynamic routes.
Example of generateStaticParams
:
tsxCopyEdit// pages/posts/[slug].tsx
export async function generateStaticParams() {
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
return posts.map(post => ({
slug: post.slug
}));
}
export default function Post({ post }) {
return <div>{post.title}</div>;
}
In this example:
generateStaticParams
dynamically generates a list ofslug
values that represent the blog posts to be rendered at build time.- Next.js uses this to create the corresponding static pages for each
slug
.
3. What is revalidate
in Next.js?
In Next.js, revalidate
is used to specify how often a page should be regenerated after the initial build. The revalidate
option can be used in conjunction with generateStaticParams
to periodically update static pages without requiring a full rebuild of the entire site.
This allows you to keep your dynamic content up-to-date by regenerating static pages based on a time interval, ensuring users always get the latest content while retaining the benefits of static generation.
Example of revalidate
:
tsxCopyEdit// pages/posts/[slug].tsx
export async function generateStaticParams() {
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
return posts.map(post => ({
slug: post.slug
}));
}
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: 60, // Regenerate the page every 60 seconds
};
}
export default function Post({ post }) {
return <div>{post.title}</div>;
}
In this example:
revalidate: 60
tells Next.js to regenerate the page after 60 seconds, allowing for fresh content while using static generation.
4. How generateStaticParams
and revalidate
Work Together
When used together, generateStaticParams
and revalidate
offer a powerful solution for dynamic pages that need to be generated at build time but still require periodic updates.
generateStaticParams
is used to determine which dynamic routes need to be generated and pre-rendered at build time (like generating a list of product pages or blog posts).revalidate
allows you to set a specific time interval after which Next.js will automatically regenerate the page when it’s requested. This ensures your static pages stay fresh without the need for a complete rebuild.
The combination of these features provides a way to optimize performance and scalability while ensuring content freshness.
5. Dynamic Pages with generateStaticParams
and revalidate
Building dynamic pages with generateStaticParams
and revalidate
is especially useful in scenarios where you have a large number of pages with dynamic parameters, such as e-commerce sites or blogs that frequently update.
Consider an e-commerce website that sells products with frequently changing prices. Using generateStaticParams
will pre-render pages for each product at build time, while revalidate
ensures that price updates or stock changes are reflected without rebuilding the entire site.
Example: E-Commerce Product Pages with generateStaticParams
and revalidate
:
tsxCopyEdit// pages/products/[id].tsx
export async function generateStaticParams() {
const res = await fetch('https://api.example.com/products');
const products = await res.json();
return products.map(product => ({
id: product.id.toString()
}));
}
export async function getStaticProps({ params }) {
const res = await fetch(`https://api.example.com/products/${params.id}`);
const product = await res.json();
return {
props: { product },
revalidate: 300, // Regenerate the product page every 5 minutes
};
}
export default function Product({ product }) {
return (
<div>
<h1>{product.name}</h1>
<p>{product.price}</p>
</div>
);
}
In this example:
generateStaticParams
dynamically fetches all the products and generates paths for each product page.revalidate: 300
makes sure that each product page is regenerated every 5 minutes, ensuring the latest price and stock are displayed.
6. Best Practices for Dynamic Pages Using generateStaticParams
and `revalidate
- Use
revalidate
judiciously: Set the revalidation time based on how frequently your content changes. For instance, for frequently updated data (like prices or stock levels), use a shorter revalidation time (e.g., 60 seconds), whereas for infrequently updated data (like blog posts or product descriptions), a longer interval (e.g., 1 hour) may be appropriate. - Leverage
generateStaticParams
to limit the number of pages generated at build time. Pre-generate only the necessary pages to minimize build time and server load. - Use fallback content: When using dynamic routes with
generateStaticParams
, consider using thefallback
option to handle pages that are not pre-generated. This ensures a smoother user experience while new pages are being generated. - Test your revalidation logic: Ensure that pages are updated as expected by testing the regeneration intervals, especially if you have critical data like prices or stock levels that need to stay current.
7. Real-World Example: Building a Dynamic Product Page
Let’s consider a real-world scenario where we want to build a dynamic product page for an e-commerce store. Using generateStaticParams
and revalidate
, we can generate a static page for each product but also keep the content fresh without rebuilding the entire site.
Code Example for Dynamic Product Page:
tsxCopyEdit// pages/products/[id].tsx
export async function generateStaticParams() {
const res = await fetch('https://api.example.com/products');
const products = await res.json();
return products.map(product => ({
id: product.id.toString()
}));
}
export async function getStaticProps({ params }) {
const res = await fetch(`https://api.example.com/products/${params.id}`);
const product = await res.json();
return {
props: { product },
revalidate: 1800, // Regenerate every 30 minutes
};
}
export default function Product({ product }) {
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
<p>{product.price}</p>
</div>
);
}
In this example:
generateStaticParams
fetches a list of products to generate the necessary dynamic pages.getStaticProps
fetches product details for each page and usesrevalidate
to ensure the page is periodically updated every 30 minutes.
8. Conclusion
Using generateStaticParams
and revalidate
provides an efficient and flexible way to build dynamic pages in Next.js, especially when you want to balance performance with fresh content. By pre-rendering dynamic routes at build time and using revalidation to refresh those pages periodically, you can ensure that your application is fast, scalable, and always up-to-date.
This combination of static generation with periodic updates allows developers to optimize content delivery, reduce server load, and improve SEO, making it a powerful tool for modern web applications.