Next.js Dynamic Routes with Static Generation

mediumTypeScript

Lesson

Dynamic Routes and Static Site Generation

Dynamic routes allow you to create pages with variable segments in the URL, like /products/laptop or /users/123. In Next.js, you create dynamic routes by using square brackets in your file names, such as [slug].tsx or [id].tsx. The value inside the brackets becomes a parameter that your page component can access.

Static Site Generation (SSG) takes this concept further by pre-rendering pages at build time. When you use generateStaticParams, you're telling Next.js which dynamic routes should be generated ahead of time. This combines the flexibility of dynamic routes with the performance benefits of static pages.

The generateStaticParams function returns an array of parameter objects. Each object represents one page that should be pre-rendered. For example, if you return [{slug: 'laptop'}, {slug: 'phone'}], Next.js will generate static HTML files for both /products/laptop and /products/phone at build time.

Your page component receives these parameters through the params prop. You can use this data to fetch content, render different UI, or handle edge cases like 404 errors for unknown parameters. This pattern is common in e-commerce sites, blogs, and documentation sites where you have a known set of pages that follow the same structure.

The key benefit is performance: visitors get instant page loads because the HTML is already generated, while you maintain the flexibility to handle dynamic content based on the URL parameters.

Example
1// generateStaticParams returns route parameters to pre-render 2export async function generateStaticParams() { 3 const posts = await fetchBlogPosts(); 4 return posts.map(post => ({ id: post.id })); 5} 6 7// Page component receives the parameters 8export default function BlogPost({ params }) { 9 const { id } = params; 10 const post = getBlogPost(id); 11 12 if (!post) { 13 return <div>Post not found</div>; 14 } 15 16 return ( 17 <article> 18 <h1>{post.title}</h1> 19 <p>{post.content}</p> 20 </article> 21 ); 22}
L2This function tells Next.js which dynamic routes to pre-render
L7The params prop contains the dynamic route parameters
L10Always handle cases where the parameter doesn't match valid data

Key Takeaways

  • •generateStaticParams pre-renders dynamic routes at build time for better performance
  • •Page components receive route parameters through the params prop
  • •Always handle invalid parameters by showing appropriate error messages or 404 pages
Loading...