JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsnextjs
PrevNext
nextjs
mid
routing

How do you create dynamic routes with static generation in Next.js?

nextjs
dynamic-routes
generateStaticParams
getStaticPaths
ssg
routing
Quick Answer

Dynamic routes use bracket syntax like `[id]` in folder/file names. For static generation, use `generateStaticParams` (App Router) or `getStaticPaths` (Pages Router) to define which paths should be pre-rendered at build time.

Detailed Explanation

Dynamic Route Syntax:

  • [id] - Single dynamic segment
  • [...slug] - Catch-all (matches any number of segments)
  • [[...slug]] - Optional catch-all (matches zero or more)

Static Generation for Dynamic Routes:

App Router:

  • Use generateStaticParams() to return all paths
  • Returns array of param objects
  • Runs at build time

Pages Router:

  • Use getStaticPaths() with getStaticProps()
  • Must specify fallback behavior:
    • false: 404 for unknown paths
    • true: Generate on-demand, show loading
    • 'blocking': Generate on-demand, wait for HTML

On-Demand Generation:

  • New paths generated when first requested
  • Cached for subsequent requests
  • Great for large sites (e-commerce, blogs)

Code Examples

App Router - generateStaticParams
// app/products/[id]/page.tsx

type Props = {
  params: { id: string };
};

// Generate static paths at build time
export async function generateStaticParams() {
  const products = await fetch('https://api.example.com/products')
    .then(res => res.json());
  
  // Return array of params to pre-render
  return products.map((product: any) => ({
    id: product.id.toString(),
  }));
}

// Page component
export default async function ProductPage({ params }: Props) {
  const product = await fetch(
    `https://api.example.com/products/${params.id}`
  ).then(res => res.json());
  
  return (
    <div>
      <h1>{product.name}</h1>
      <p>${product.price}</p>
    </div>
  );
}

// Output: Pre-renders /products/1, /products/2, etc.

Resources

Dynamic Routes

docs

generateStaticParams

docs

Related Questions

How does file-based routing work in Next.js?

junior
routing

Explain the different rendering strategies in Next.js (SSR, SSG, ISR) and when to use each approach.

senior
rendering
Previous
What's the difference between Server Components and Client Components in Next.js?
Next
How do API routes work in Next.js?