Topic 7 of 39
Dynamic Routes
Overview
Dynamic routes allow you to create URLs from dynamic data, like IDs or slugs (e.g., /users/123). You create them by wrapping a folder name in square brackets [folderName].
Syntax
tsx
// Folder structure: app/users/[id]/page.tsx
// Maps to: /users/1, /users/abc, etc.
export default function UserProfile({ params }: { params: { id: string } }) {
// 'params' contains the dynamic route segments
return <h1>User Profile ID: {params.id}</h1>;
}Common Pitfalls
- Not handling cases where the dynamic parameter is invalid or missing in the database (should return a 404).
- Forgetting that
paramsis a Promise in Next.js 15+ and needs to be awaited.
Interview Questions
Q:
How do you access the dynamic segment of a URL in a Next.js App Router page?
A:
Next.js passes a params object as a prop to the page component. The keys of params match the bracketed folder names (e.g., [slug] gives params.slug).
Real-World Example
Fetching blog post data based on the URL slug.
example
tsx
// app/blog/[slug]/page.tsx
import { notFound } from 'next/navigation';
import db from '@/lib/db';
export default async function BlogPost({ params }: { params: { slug: string } }) {
const post = await db.post.findUnique({ where: { slug: params.slug } });
if (!post) {
notFound(); // Triggers the nearest not-found.tsx
}
return (
<article>
<h1>{post.title}</h1>
<p>{post.content}</p>
</article>
);
}Check Your Knowledge
Test your understanding of Dynamic Routes with these quick questions.