Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 72 ยท Routing

Dynamic Routes

Turn a folder name like [slug] into a route that matches many URLs. Learn how params arrive as a promise, how to type them, and how generateStaticParams fits in.

A blog with ten posts does not need ten folders. It needs one page that reads the post name from the URL and shows the right content. In Next.js you build that page with a dynamic route: a folder whose name is wrapped in square brackets, such as app/blog/[slug]/page.tsx. The brackets turn the folder name into a variable.

This lesson shows how a bracket folder matches URLs, how the matched value reaches your component as params, why params is a promise in modern Next.js, and how to tell Next.js which pages to build ahead of time. You should already know File-Based Routing and Pages and Layouts.

Real framework or stand-in? Next.js itself cannot run on this site, so every tsx snippet in this lesson is read-only. The live examples are small stand-ins written in plain JavaScript that run on our code runner. They re-create the rules (how a URL is matched, how static params are chosen), not the real router.

A bracket folder is a variable

The folder app/blog/[slug]
The URL /blog/hello-world
The params { slug: 'hello-world' }

One page file serves every URL that fits the pattern.

1 / 2

Creating a dynamic segment

Put the variable name between square brackets and create a page.tsx inside. Here is a typical shop layout:

TEXT
app/
  blog/
    page.tsx            -> /blog
    [slug]/
      page.tsx          -> /blog/anything
  shop/
    [category]/
      [id]/
        page.tsx        -> /shop/shoes/42
  users/
    [userId]/
      posts/
        [postId]/
          page.tsx      -> /users/7/posts/19

Three things are worth noticing:

  • A dynamic segment matches exactly one URL segment. /blog/hello matches [slug]; /blog/2026/hello does not (that needs a catch-all route).
  • It never matches an empty segment. /blog is handled by app/blog/page.tsx, not by [slug].
  • You can nest as many dynamic segments as you like, and each one needs its own name. Two segments in the same position cannot have different names ([id] next to [slug] is an error).

The folder name is the name of the variable. It is not special in any other way: [slug], [id] and [postId] all work the same.

Reading params in a page

The matched values arrive in your page component as the params prop. In Next.js 15 and 16, params is a promise, so the component must be async and you await it:

TSX
// app/blog/[slug]/page.tsx (read-only)
import { notFound } from 'next/navigation';
import { getPost } from '@/lib/posts';

export default async function PostPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const post = await getPost(slug);

  if (!post) {
    notFound();
  }

  return (
    <article>
      <h1>{post.title}</h1>
      <p>{post.summary}</p>
    </article>
  );
}

Why a promise? Next.js wants to start rendering parts of the page before it knows everything about the request. A promise lets the framework hand your component control early and resolve the values when they are ready. Older versions (14 and below) passed a plain object, and Next.js 15 kept a temporary compatibility layer that warned when you read it directly. Version 16 removed that layer, so params.slug without await no longer works. If you are upgrading an old project, the upgrade lesson covers the codemod.

A few habits keep dynamic pages safe:

  • Treat params as untrusted text. The URL is typed by visitors. If id must be a number, convert it and handle the failure: const id = Number(rawId); if (!Number.isInteger(id)) notFound();.
  • Decode when you compare. Characters such as spaces or non-English letters can arrive percent-encoded (caf%C3%A9). Use decodeURIComponent before looking the value up.
  • Call notFound() for unknown values. It renders your not-found.tsx with a 404 status. See loading.tsx, error.tsx and not-found.tsx.

The same promise shape appears in other places that receive params: generateMetadata, layouts (which receive the params of their own segment and the segments above it) and route handlers. In a client component, you cannot make the component async, so you unwrap the promise with React's use() hook, or read the values with the useParams() hook from next/navigation:

TSX
// app/blog/[slug]/comments.tsx (read-only)
'use client';

import { useParams } from 'next/navigation';

export function CommentsHeading() {
  const { slug } = useParams<{ slug: string }>();
  return <h2>Comments on {slug}</h2>;
}

Typing params

Writing Promise<{ slug: string }> by hand works, but it repeats the folder structure inside your code, and a typo goes unnoticed. Recent Next.js versions generate route-aware helper types (PageProps, LayoutProps and RouteContext) when you run next dev, next build or next typegen. They are available globally, so you do not import them:

TSX
// app/shop/[category]/[id]/page.tsx (read-only)
export default async function ProductPage(
  props: PageProps<'/shop/[category]/[id]'>,
) {
  const { category, id } = await props.params;

  return (
    <h1>
      {category} #{id}
    </h1>
  );
}

The route string you pass must match an existing route, and TypeScript derives params from it. If you rename a folder, the type changes with it and the compiler points at every place you need to fix. TypeScript, ESLint and Typed Routes goes deeper.

How a URL picks a dynamic route

Next.js sorts routes by specificity, so a fixed name beats a variable. Given app/blog/new/page.tsx and app/blog/[slug]/page.tsx, the URL /blog/new goes to the static page, and every other /blog/something goes to the dynamic one. Try the stand-in below. It turns file paths into patterns, matches a URL against them and prints the params it found. The route list includes a static /blog/new so you can see the priority rule.

Node.js Match URLs against dynamic folders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output line by line. /blog/new lands on the static file because it has more fixed segments. /blog/cafรฉ-au-lait shows the decoded value, which is why the stand-in calls decodeURIComponent once. The last URL has three segments, and no pattern with three segments matches, so it is a 404. That is exactly what happens in a real app until you add a catch-all.

generateStaticParams: build pages ahead of time

By default, a dynamic page is rendered when someone asks for it. If you know the list of values in advance (all blog slugs, all product ids), you can tell Next.js to render those pages during next build, so the first visitor already gets ready-made HTML. You export a function named generateStaticParams from the same file. It returns an array with one object per page, and each object has the same keys as your folder names:

TSX
// app/blog/[slug]/page.tsx (read-only)
import { getAllPosts } from '@/lib/posts';

export async function generateStaticParams() {
  const posts = await getAllPosts();
  return posts.map((post) => ({ slug: post.slug }));
}

What about a slug that was not in that list, for example a post published after the last build? That is controlled by the dynamicParams export:

TSX
// app/blog/[slug]/page.tsx (read-only)
export const dynamicParams = false; // unknown slugs become a 404
  • dynamicParams = true (the default): unknown values are rendered on demand when first requested.
  • dynamicParams = false: only the values returned by generateStaticParams exist; everything else is a 404.

For nested dynamic segments, a child can use the parent's values: app/shop/[category]/[id] can export generateStaticParams({ params }) and receive the category the parent produced, so you fetch products per category instead of one huge list. The full story of build-time rendering, including how this interacts with caching, is in Static Generation and generateStaticParams.

The second stand-in plays the same decision game. It builds the list, then decides what each request would get. Notice that params is a promise here, just like in the real framework.

Node.js generateStaticParams and dynamicParams

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

With dynamicParams = true, draft-ideas was skipped at build time but still renders on demand (the page code finds it), published-later works without a rebuild, and missing is a 404 because the page itself decided it. With false, anything not in the build list is a 404 straight away. Choose false when the list is closed and a surprise slug should never reach your database.

Common mistakes

  • Forgetting await. Reading params.slug directly gives undefined (or an error in version 16). Always const { slug } = await params.
  • Expecting numbers. params.id is "42", never 42. Convert and validate it.
  • Using [id] where a list is needed. A single bracket matches one segment. For /docs/a/b/c, read the next lesson.
  • Mixing names. app/users/[id] and app/users/[userId] cannot coexist; pick one name per position.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which URL does app/blog/[slug]/page.tsx match?

    A dynamic segment matches exactly one non-empty URL segment. /blog is handled by app/blog/page.tsx, and a URL with two segments after /blog needs a catch-all route.
  2. 2. In Next.js 15 and 16, how does a server page read the slug from app/blog/[slug]/page.tsx?

    params is a promise, so the component is async and awaits it. Reading it synchronously was a deprecated shortcut in 15 and was removed in 16.
  3. 3. A project has app/blog/new/page.tsx and app/blog/[slug]/page.tsx. Which page renders /blog/new?

    Next.js orders routes by specificity. A fixed name beats a variable, so only /blog/something-else reaches the dynamic page.
  4. 4. What does export const dynamicParams = false do?

    With dynamicParams set to false, only the paths produced by generateStaticParams exist. The default, true, renders unknown values on demand.
  5. 5. Which is the right way to read the route params inside a client component?

    Client components cannot be async. useParams returns the current values, and use() can unwrap a promise passed down from a server component.

Summary

  • A folder wrapped in brackets, such as [slug], is a dynamic segment: it matches exactly one non-empty URL segment, and the name becomes the key in params.
  • In Next.js 15 and 16, params is a promise: make the page async and await it, or use use() / useParams() in client components.
  • Values are strings and come from visitors: validate them, decode them when needed, and call notFound() for unknown ones.
  • The generated PageProps<'/route'> helper types params from the route string, so renames are caught by TypeScript.
  • Static segments beat dynamic ones when both match.
  • generateStaticParams lists the pages to build ahead of time; dynamicParams decides whether other values render on demand or return a 404.

Next: Catch-All and Optional Catch-All Routes