Next.js foundations · Lesson 3 of 16
Dynamic routes
[slug] and params, searchParams, generateStaticParams, and notFound.
You won't make a folder per course. A folder named in square brackets, [slug], matches any value in that URL segment, and the value reaches the page in params.
// app/courses/[slug]/page.tsx matches /courses/react, /courses/sql, …
import { notFound } from "next/navigation"
import { getCourse } from "@/lib/courses"
export default async function CoursePage({
params,
searchParams,
}: {
params: Promise<{ slug: string }>
searchParams: Promise<{ tab?: string }>
}) {
const { slug } = await params // "react"
const { tab = "overview" } = await searchParams // /courses/react?tab=lessons
const course = await getCourse(slug)
if (!course) notFound() // shows app/not-found.tsx with a 404 status
return <h1>{course.title} · {tab}</h1>
}| Folder | Matches | params |
|---|---|---|
[slug] | /courses/react | { slug: "react" } |
[...parts] | /docs/a/b/c | { parts: ["a", "b", "c"] } |
[[...parts]] | /docs | { } (optional) |
[slug]/lessons/[id] | /courses/sql/lessons/4 | { slug: "sql", id: "4" } |
generateStaticParams
// Build these course pages ahead of time instead of on each request
export async function generateStaticParams() {
const courses = await getAllCourses()
return courses.map((c) => ({ slug: c.slug })) // [{ slug: "react" }, { slug: "sql" }, …]
}Spot the bug
This page shows undefined in Next.js 16. Which line?
Exercise
Write matchRoute(pattern, url) returning the params object when the URL matches, or null otherwise. Pattern segments in [ ] match any value. Print the results with JSON.stringify.
{"slug":"react"}
{"slug":"sql","id":"4"}
nullfunction matchRoute(pattern, url) {
return null
}
console.log(JSON.stringify(matchRoute("/courses/[slug]", "/courses/react")))
console.log(JSON.stringify(matchRoute("/courses/[slug]/lessons/[id]", "/courses/sql/lessons/4")))
console.log(JSON.stringify(matchRoute("/courses/[slug]", "/blog/react")))Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.