पाठ 5 / 25

Dynamic Routes and params

One file, many URLs.

Square-bracket segments

A folder named [id] matches any value in that position (/products/1, /products/2). The page receives params; in current Next.js versions params is a Promise, so you await it in an async Server Component. generateStaticParams returns the list of params to prerender at build time; other values can still be rendered on demand unless you disable that. Catch-all segments ([...slug]) match several path parts. Next.js changes quickly between major versions; check the docs for your version (they ship inside node_modules/next/dist/docs).

A dynamic product page

This file is from a small demo store I built with Next.js 16.3.8, React 19.3 and TypeScript; next build compiled and type-checked it successfully. It prerenders products 1 to 3 with generateStaticParams, builds the page title with generateMetadata, awaits params, and calls notFound() for unknown ids.

import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getProduct, getProducts } from "@/lib/data";

type Props = { params: Promise<{ id: string }> };

export async function generateStaticParams() {
  const products = await getProducts();
  return products.map((p) => ({ id: p.id }));     // prerender these at build time
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { id } = await params;
  const product = await getProduct(id);
  return { title: product ? product.name : "Not found" };
}

export default async function ProductPage({ params }: Props) {
  const { id } = await params;
  const product = await getProduct(id);
  if (!product) notFound();
  return <h1>{product.name} costs Rs {product.price}</h1>;
}

Requesting a prerendered product, run

I built the demo store with next build (Next.js 16.3.8), started it with next start and requested pages with curl; the output is copied from that run, trimmed to the relevant lines. The page title combines the product name with the layout's template.

curl -s http://localhost:3917/products/2

Output:

<title>Fountain pen | Stationery Shop</title>
<h1>Fountain pen costs Rs 899</h1>

त्वरित जाँच: What does generateStaticParams do?

  • Validates form input
  • Lists the param values to prerender as static pages at build time
  • Creates API keys
  • Adds CSS
Answer

Lists the param values to prerender as static pages at build time — Prerender known pages ahead of time.