Skip to content

Dynamic Routes

The Course
•
20 min study

One file, many pages

A site with a page per topic, product or post can't have a folder for each: they come from data, and there might be thousands. A dynamic segment is a folder whose name is in square brackets. It matches any one part of the address.

A page per topic Next.js · 5 files
import Link from "next/link"; import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <nav> <Link href="/">Topics</Link> </nav> </header> {children} </body> </html> ); } import Link from "next/link"; import { getTopics } from "@/lib/topics.js"; export default async function HomePage() { const topics = await getTopics(); return ( <main> <h1>Topics</h1> <ul> {topics.map((topic) => ( <li key={topic.slug}> <Link href={`/topics/${topic.slug}`}>{topic.title}</Link> </li> ))} </ul> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } header, main, footer { max-width: 36rem; margin: 0 auto; padding: 0.75rem 1rem; } header { border-bottom: 1px solid #d6dde6; } nav { display: flex; gap: 1rem; } a { color: #06617f; } h1 { margin: 0.5rem 0; } .muted { color: #5b6876; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } nav a[aria-current="page"] { font-weight: 700; text-decoration: none; color: #1c2430; } import { getTopic } from "@/lib/topics.js"; // [slug] in the folder name matches any one segment: /topics/routing, // /topics/layouts, and so on. export default async function TopicPage({ params }) { const { slug } = await params; const topic = await getTopic(slug); return ( <main> <h1>{topic.title}</h1> <p>{topic.summary}</p> <p className="muted"> Day {topic.day} · {topic.minutes} minutes · slug: {slug} </p> </main> ); } // Pretend database of topics, looked up by their slug: the part of the URL // that names them. const topics = [ { slug: "routing", title: "Routing", day: 1, minutes: 20, summary: "Folders become pages." }, { slug: "layouts", title: "Layouts", day: 1, minutes: 20, summary: "Shared parts that wrap pages." }, { slug: "server-components", title: "Server components", day: 2, minutes: 20, summary: "Components that run on the server." }, { slug: "client-components", title: "Client components", day: 2, minutes: 20, summary: "Components that respond in the browser." }, { slug: "dynamic-routes", title: "Dynamic routes", day: 3, minutes: 25, summary: "One file for many pages." }, ]; const wait = () => new Promise((resolve) => setTimeout(resolve, 100)); export async function getTopics() { await wait(); return topics; } export async function getTopic(slug) { await wait(); return topics.find((topic) => topic.slug === slug) ?? null; }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.

Follow a few topics, and watch the address bar.

AddressFileslug
/topics/routingapp/topics/[slug]/page.jsx"routing"
/topics/layoutsthe same file"layouts"

Reading params

JavaScript
export default async function TopicPage({ params }) {
  const { slug } = await params;
  const topic = await getTopic(slug);
  …
}

Every page receives params: the values of its dynamic segments, named after the folders. It's a promise, so you await it before reading. Then the page looks up its data, the same way for every slug.

slug is just a name. [id] would give an id property after unwrapping params with await. "Slug" is the usual name for the readable part of a URL, such as dynamic-routes.

The @ in the import

JavaScript
import { getTopic } from "@/lib/topics.js";

@/ means "from the project's top folder". Without it, this file would need ../../../lib/topics.js, three levels up. Projects made by create-next-app set up @/ for you, and so do this course's downloads.

Predict

Two mistakes to try, one at a time:

  1. Visit /topics/nope.
  2. Change const { slug } = await params; to const slug = params.slug;, then follow a topic.
Check your prediction

Both crash with Cannot read properties of null (reading 'title').

  1. There's no topic called nope, so getTopic returns null.
  2. params is a promise, so params.slug is undefined, and no topic has that slug. The console also names the cause, in the same words as real Next.js: Route "/topics/[slug]" used params.slug. params is a Promise and must be unwrapped with await or React.use() before accessing its properties.

Undo the second change. The next lesson handles the first one properly.

Exercise

Link back

At the bottom of each topic page, add a link ← All topics back to /.

Your working space Next.js · 5 files
import Link from "next/link"; import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <nav> <Link href="/">Topics</Link> </nav> </header> {children} </body> </html> ); } import Link from "next/link"; import { getTopics } from "@/lib/topics.js"; export default async function HomePage() { const topics = await getTopics(); return ( <main> <h1>Topics</h1> <ul> {topics.map((topic) => ( <li key={topic.slug}> <Link href={`/topics/${topic.slug}`}>{topic.title}</Link> </li> ))} </ul> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } header, main, footer { max-width: 36rem; margin: 0 auto; padding: 0.75rem 1rem; } header { border-bottom: 1px solid #d6dde6; } nav { display: flex; gap: 1rem; } a { color: #06617f; } h1 { margin: 0.5rem 0; } .muted { color: #5b6876; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } nav a[aria-current="page"] { font-weight: 700; text-decoration: none; color: #1c2430; } import { getTopic } from "@/lib/topics.js"; // [slug] in the folder name matches any one segment: /topics/routing, // /topics/layouts, and so on. export default async function TopicPage({ params }) { const { slug } = await params; const topic = await getTopic(slug); return ( <main> <h1>{topic.title}</h1> <p>{topic.summary}</p> <p className="muted"> Day {topic.day} · {topic.minutes} minutes · slug: {slug} </p> </main> ); } // Pretend database of topics, looked up by their slug: the part of the URL // that names them. const topics = [ { slug: "routing", title: "Routing", day: 1, minutes: 20, summary: "Folders become pages." }, { slug: "layouts", title: "Layouts", day: 1, minutes: 20, summary: "Shared parts that wrap pages." }, { slug: "server-components", title: "Server components", day: 2, minutes: 20, summary: "Components that run on the server." }, { slug: "client-components", title: "Client components", day: 2, minutes: 20, summary: "Components that respond in the browser." }, { slug: "dynamic-routes", title: "Dynamic routes", day: 3, minutes: 25, summary: "One file for many pages." }, ]; const wait = () => new Promise((resolve) => setTimeout(resolve, 100)); export async function getTopics() { await wait(); return topics; } export async function getTopic(slug) { await wait(); return topics.find((topic) => topic.slug === slug) ?? null; }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

Navigation is ordinary JSX on the page. A fixed destination needs no client state or router hook.

Hint 2: a first step

The topic page is a server component; Link works in both kinds. Import it from next/link.

Show one solution
JavaScript
import Link from "next/link";
JSX
<p>
  <Link href="/">← All topics</Link>
</p>

Was this article helpful?

Your response is saved on this device.