Sikau

Next.js · Day 5 · about 30 min

Dynamic routes

One page file for many URLs: [slug].

A page per dish — from one file

You won't write a file for every dish. A folder named in brackets, like [slug], matches *any* value in that part of the URL — a dynamic route. The page receives the value in params.

params is a promise

import { getDish } from "@/lib/data";
import { notFound } from "next/navigation";

export default async function DishPage({ params }) {
  const { slug } = await params;
  const dish = await getDish(slug);
  if (!dish) notFound();

  return (
    <article>
      <h1>{dish.name}</h1>
      <p>{dish.description}</p>
      <p>Rs {dish.price}</p>
    </article>
  );
}
  • [...slug] catches several segments: /docs/a/b → slug: ["a", "b"].
  • generateStaticParams() can list the values to pre-render at build time.
  • Query strings like ?sort=price come in a separate searchParams prop (also a Promise).

The rest of this lesson

  • Static or dynamic renderingexplain
  • Slugs, not idsexplain
  • What's params?predict
  • Folder → matchesmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 19 lessons of Next.js