Thuta Learning
Next.js
IntermediateWeb DevelopmentIntermediate

Dynamic Routes and Params

Next.jsLesson 830 min

What you'll walk away with

  • Predict which URLs [id], [...slug] and [[...slug]] folders match and what lands in params
  • Await the params Promise in a Server Component page and read it with the right type
  • Call notFound() for a missing record so the nearest not-found.tsx is shown
  • Explain which paths generateStaticParams prebuilds at build time

Explain it simply

Dynamic routes in plain language

If the Myanmar Notes app needed one page file per note, a thousand notes would mean a thousand files. A dynamic route works like a form with a blank in it: you write one page template, and the id in the URL fills in the blank.

Once a folder name is written in square brackets, such as app/notes/[id]/, Next.js treats that segment as 'any text goes here'. Opening /notes/routing gives id the value "routing", opening /notes/caching gives "caching", and the page code is the same file both times.

Problem → Why → Solution

The problem: an unreadable id and a crash on missing notes

Imagine this is your first attempt at the page. It has two bugs. First, it treats params as a plain object, but in the current App Router params is a Promise, so params.id is a TypeScript error. Second, when someone types /notes/does-not-exist, getNote returns undefined and reading note.title crashes the whole page with an error.

app/notes/[id]/page.tsx
import { getNote } from "@/lib/notes";

export default async function NotePage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const note = await getNote(params.id); // params is a Promise: no .id on it
  return <h1>{note.title}</h1>; // TypeError when the note does not exist
}

Why this matters

A URL is input that users can type however they like. It is not enough for the page to work when the id is valid; it must also say 'this note does not exist' politely when the id is wrong. With notFound() the user sees a clear 404 page, and search engines stop indexing a URL that has nothing behind it.

Core concept: the folder name becomes a params key

The text inside the brackets becomes the key in the params object. For app/notes/[id]/page.tsx, params is { id: string }; name the folder [noteId] and the key is noteId. Values from the URL always arrive as strings: even for /notes/42, id is the string "42", not the number 42. If you need a number, convert it yourself and check for NaN. Anything else you place in the [id] folder, such as a loading.tsx or a not-found.tsx, then serves every note at once.

Since Next.js 15, params is a Promise, so inside an async Server Component you write const { id } = await params. In Next.js 14 and earlier it was a plain object, which is why older tutorials online read params.id directly. In a Client Component page, use React's use(params) or the useParams() hook instead. The Dynamic Segments page of the Next.js docs has the details.

FolderExample URLparams
app/notes/[id]/notes/routing{ id: "routing" }
app/docs/[...slug]/docs/a/b{ slug: ["a", "b"] }
app/docs/[[...slug]]/docs{ slug: undefined }

When the data is missing, import notFound() from next/navigation and call it. It throws a special error, so nothing after it runs and Next.js renders the nearest not-found.tsx instead. Its return type is never, which means below if (!note) notFound(); TypeScript knows note is no longer undefined and lets you read note.title without complaint.

Dynamic segments can also be stacked: app/[category]/[item]/page.tsx gives { category: "books", item: "atlas" } for /books/atlas. The same params Promise reaches not only the page but also layout.tsx, route.ts and generateMetadata (lesson 11). A layout does not see params from segments below it, only those from its own segment and above.

The journey of an id from URL to page
  1. URL /notes/routing arrives
  2. [id] folder captures "routing"
  3. await params yields { id }
  4. getNote(id) looks up the record
  5. Missing: notFound(); found: render

Values in params are text the user typed; trust them only after the data layer confirms them.

General pattern

app/<segment>/[param]/page.tsx
export default async function Page({
  params,
}: {
  params: Promise<{ param: string }>;
}) {
  const { param } = await params;
  const item = await loadItem(param);
  if (!item) notFound();
  return <ItemView item={item} />;
}

Keep the folder name and the params key identical, await params, ask the data layer, and call notFound() before rendering when nothing comes back.

Worked example: a note detail page

Put this file at app/notes/[id]/page.tsx. getNote is the project's data-layer function: it looks up a note by id and returns undefined when there is none. Notice how this version fixes both bugs from the problem section.

tsx
import { notFound } from "next/navigation";
import { getNote } from "@/lib/notes";

export default async function NotePage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const note = await getNote(id);

  if (!note) notFound();

  return (
    <article>
      <h1>{note.title}</h1>
      <p>{note.content}</p>
    </article>
  );
}

Code breakdown

  1. Type the Promiseparams: Promise<{ id: string }>;

    params is typed as a Promise, so reading .id without awaiting is flagged by the compiler immediately. The key name id must match the [id] folder.

  2. Unwrap the paramsconst { id } = await params;

    The Promise is awaited and id is destructured out of it. This works because the component itself is async.

  3. Ask the data layerconst note = await getNote(id);

    Because this runs on the server, it can ask the database or API directly. The result is a Note or undefined.

  4. Guard with notFoundif (!note) notFound();

    With no note, rendering stops here and the not-found UI is shown. Because notFound() returns never, TypeScript knows note is defined on the lines below.

  5. Render the record<h1>{note.title}</h1>

    Reaching this line means the note really exists, so its title and content can be shown safely.

You should see
The note detail shows up for an id that exists, and 404 UI shows up for an id that doesn't.

generateStaticParams: prebuilding paths at build time

By default a dynamic page is rendered when a request arrives. If you want the most-visited notes to have ready-made HTML from build time, export generateStaticParams from the page file. It returns an array of params objects, and Next.js renders each of those paths during the build. Ids not in the list are still rendered on request (unless you export dynamicParams = false, which turns them into 404s).

app/notes/[id]/page.tsx
import { getPopularNoteIds } from "@/lib/notes";

// Each object is one set of params; ids must be strings.
export async function generateStaticParams() {
  const ids = await getPopularNoteIds(); // e.g. ["routing", "caching"]
  return ids.map((id) => ({ id }));
}

With Cache Components enabled

In a project with Cache Components (lesson 15) turned on, params without generateStaticParams count as runtime data, and the part that reads them needs a Suspense boundary or a loading.tsx. Lesson 15 covers that rule in detail.

In real projects

Dynamic routes in real projects

Almost every detail page is a dynamic route: /products/[slug] in a shop, /posts/[slug] on a blog, /users/[username] in a social app. When teams build these pages for production, a few habits show up again and again.

  • URLs use a readable slug such as nextjs-routing-basics instead of a database id, which makes links easier to share and clearer in search results.
  • params are validated before the database is asked: if Number(id) is NaN where a numeric id is expected, the page calls notFound() without running a query.
  • A shop prebuilds its few best-selling products with generateStaticParams and lets the rest render on request, which also keeps build times short.
  • For data that belongs to a user, such as /invoices/[id], the page checks that the logged-in user owns the record, not merely that it exists; lesson 20 picks this up.

Common mistakes

Common mistakes with dynamic routes

Using params without awaiting it

params.id copied from a Next.js 14 era tutorial is now a property read on a Promise, which gives a type error or undefined. Next.js 15 temporarily allowed synchronous access with a warning as a migration aid, but do not rely on it: always use await params or use(params).

Rendering undefined when the record is missing

Without an if (!note) check, an unknown id causes 'Cannot read properties of undefined' and the user sees an error page instead of a 404. Writing return null is not much better: it sends a blank page with a 200 status. Only notFound() gives the proper 404 UI plus a noindex tag.

A folder name that does not match the destructured key

With a folder named [noteId] and code that says const { id } = await params, id is undefined and getNote(undefined) never finds anything. If every page is a 404, compare the folder name with the params type first.

Best practices

Best practices

  • Name folders clearly: [noteSlug] says more about what arrives than [id].
  • Validate params before handing them to the data layer and call notFound() early when they are malformed.
  • Give each detail route its own not-found.tsx with a link back to the list page.

Mini challenge

Mini challenge: a user profile page

Write app/users/[username]/page.tsx. Look up the user by the username in the URL, show their name and bio when found, and show the 404 page otherwise. Prebuild two users at build time.

  • Type params as Promise<{ username: string }> and await it
  • Call notFound() when the user does not exist
  • generateStaticParams must return "aye" and "min"
  • Show @username in the heading
app/users/[username]/page.tsx
import { notFound } from "next/navigation";

type User = { username: string; name: string; bio: string };

const users: User[] = [
  { username: "aye", name: "Aye Chan", bio: "Writes about CSS." },
  { username: "min", name: "Min Thu", bio: "Learning Next.js." },
];

// TODO: export generateStaticParams that returns one object per user

// TODO: type the props so params is a Promise of { username: string }
export default async function UserPage(props) {
  // TODO: await params and find the user
  // TODO: call notFound() when there is no match
  // TODO: render an <h1> with @username, then the name and bio
}

Expected: /users/aye shows an "@aye" heading with Aye Chan and the bio. /users/nobody shows the not-found UI. In the next build output, /users/aye and /users/min appear as prerendered paths.

Show hint

generateStaticParams only needs to return an array of objects such as users.map((u) => ({ username: u.username })). users.find(...) returns User | undefined, so guard with notFound() before reading properties.

Show solution
app/users/[username]/page.tsx
import { notFound } from "next/navigation";

type User = { username: string; name: string; bio: string };

const users: User[] = [
  { username: "aye", name: "Aye Chan", bio: "Writes about CSS." },
  { username: "min", name: "Min Thu", bio: "Learning Next.js." },
];

export async function generateStaticParams() {
  return users.map((user) => ({ username: user.username }));
}

export default async function UserPage({
  params,
}: {
  params: Promise<{ username: string }>;
}) {
  const { username } = await params;
  const user = users.find((u) => u.username === username);
  if (!user) notFound();

  return (
    <section>
      <h1>@{user.username}</h1>
      <p>{user.name}</p>
      <p>{user.bio}</p>
    </section>
  );
}

Quick quiz 1 / 3

Given app/docs/[...slug]/page.tsx, what does await params give for /docs/guides/routing?

Quick quiz 2 / 3

The folder is app/notes/[noteId]/ and the page does const { id } = await params; const note = await getNote(id);. What happens?

Quick quiz 3 / 3

What happens when if (!note) notFound(); runs with no note?

What to remember

  • A bracket folder like [id] captures a URL segment, and the bracket name becomes the params key.
  • Since Next.js 15 params is a Promise: await it in Server Components, use(params) in Client Components.
  • URL values are strings (string arrays for catch-alls) and must be validated like any user input.
  • Call notFound() for missing records, and prebuild popular paths with generateStaticParams.

Next.js — Layouts and Pages — Next.js

Next.js — Layouts and Pages — Next.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Dynamic Routes and Params | Thuta Learning