Menu

Dynamic Routes

Lesson 4: Dynamic Routes

What is a dynamic route?

A dynamic route creates many pages from one file. Wrap a folder name in square brackets, and that segment accepts any value.

Folder Matches params value
app/courses/[slug]/page.tsx /courses/sql { slug: 'sql' }
app/blog/[year]/[slug]/page.tsx /blog/2026/hooks { year: '2026', slug: 'hooks' }
app/docs/[...path]/page.tsx (catch-all) /docs/a/b/c { path: ['a', 'b', 'c'] }
app/shop/[[...filters]]/page.tsx (optional catch-all) /shop and /shop/a/b {} or { filters: ['a', 'b'] }

Example

// app/courses/[slug]/page.tsx
import { notFound } from 'next/navigation';
import { getCourse } from '@/lib/courses';

export default async function CoursePage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const course = await getCourse(slug);

  if (!course) notFound();

  return (
    <article>
      <h1>{course.title}</h1>
      <p>{course.lessons} lessons · {course.level}</p>
    </article>
  );
}

Prerender popular courses at build time:

export async function generateStaticParams() {
  const courses = await getAllCourses();
  return courses.map((course) => ({ slug: course.slug }));
}

How it works

  1. The page is async, so it can wait for params and for data.
  2. params is a Promise since Next.js 15. Synchronous access was removed in Next.js 16.
  3. notFound() stops rendering and shows the nearest not-found.tsx.
  4. generateStaticParams returns a list of params to prerender at build time. Slugs not in the list are rendered on first request.
  5. Values in params are always strings. Convert them when you need numbers: Number(id).

Tip: Next.js generates a global PageProps type helper, so you can write props: PageProps<'/courses/[slug]'> and get typed params automatically.

Common mistakes

Mistake Effect Fix
params.slug without await Type error or undefined const { slug } = await params
Not handling missing records Crash or empty page Call notFound() when data is missing
Treating params.id as a number Comparisons fail ('5' !== 5) Convert with Number() and validate
Two dynamic folders at the same level ([id] and [slug]) Build error Use one name per level

Key takeaways

  • [name] folders create dynamic segments; [...name] catches multiple segments.
  • Always await params, validate the value, and call notFound() for missing data.

Try it: Create app/courses/[slug]/page.tsx that looks up a course in a local array and shows a 404 for unknown slugs.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details