
Next.js offers powerful dynamic routing combined with static generation, allowing you to build fast, scalable websites with pages generated at build time or on-demand. Understanding how to combine these features helps you optimize both performance and SEO.
Dynamic Routes
Dynamic routes allow you to create pages based on variable paths. For example, a blog can have /posts/[slug] pages, where [slug] represents each post’s unique identifier.
Next.js automatically maps files in the pages or app folder using [param] syntax:
// app/posts/[slug]/page.tsx
import { getPost } from '@/lib/posts'export default async function PostPage({ params }) {
const post = await getPost(params.slug)
return <article>{post.content}</article>
}Dynamic routes can also include catch-all segments ([...params]) for nested paths.
Static Generation (SSG)
Static Generation pre-renders pages at build time, producing HTML for each route ahead of user requests. This improves load times and SEO since pages are fully rendered and cached.
You can combine dynamic routes with static generation using functions like getStaticPaths (for the pages folder) or by generating pages in the app router with generateStaticParams.
// pages/posts/[slug].tsx
export async function getStaticPaths() {
const posts = await fetchAllPosts()
return {
paths: posts.map(post => ({ params: { slug: post.slug } })),
fallback: false,
}
}
This ensures all blog posts are statically generated at build time.
Best Practices
Pre-generate frequently visited pages: Use static generation for pages that don’t change often.
Use ISR for dynamic content: Incremental Static Regeneration allows you to rebuild pages after deployment, combining static performance with up-to-date content.
Optimize data fetching: Fetch only necessary data during build time to minimize build duration.
Fallback handling: When using dynamic routes with fallback options, show loading states for pages that are generated on-demand.
Summary
Dynamic routing and static generation are core features of Next.js that let you build fast, SEO-friendly, and scalable websites. Use dynamic routes to structure variable paths, and static generation to pre-render pages for better performance. For frequently changing content, consider Incremental Static Regeneration to keep pages up-to-date without sacrificing speed.