[Next.js 15] - Part 7. Dynamic Routes with Parameters

Ace Lennox
In Next.js, dynamic routes allow you to create pages that display different content based on dynamic parameters. This is useful for building pages from external data sources, such as blog posts, products...
1. What Are Dynamic Routes?
Dynamic routes enable a page to show different content depending on dynamic parameters. For instance, a blog page can display various articles based on the post ID or slug (a unique identifier).
Where Does Dynamic Data Come From?
Markdown files
Databases
External APIs
2. How to Create Dynamic Routes
Directory Structure
Create a new folder in the
app
directory.Name the folder containing the dynamic parameter with square brackets (
[]
).Inside this folder, create a
page.js
file.
For example, to create a blog page that renders content based on a slug:
Folder:
/app/blog/[slug]/page.js
[slug]
is the dynamic parameter.
Example Structure
/app
└── blog
└── [slug]
└── page.js
3. Implementation
In page.js
, you can use the dynamic parameter to render content. Here’s a basic example:
// /app/blog/[slug]/page.js
export default function BlogPage({ params }) {
const { slug } = params;
return (
<div>
<h1>Blog Post: {slug}</h1>
<p>Dynamic content will be displayed here.</p>
</div>
);
}
params
: An object containing the dynamic parameters from the URL.slug
: The dynamic parameter name (matches the folder name in square brackets).
4. Testing the Dynamic Route
Run the development server:
npm run dev
Navigate to
/blog
→ Result: 404 Not Found (because the dynamic parameterslug
is required).Navigate to
/blog/first
→ Result: The page displays the slugfirst
.
5. Fetching Dynamic Data
You can use the slug
to fetch data from a database or other sources. For example:
import { getBlogPost } from '@/lib/blog'; // Example function to fetch a blog post
export default async function BlogPage({ params }) {
const { slug } = params;
const post = await getBlogPost(slug);
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
);
}
6. Prefetching and Dynamic Routes
Next.js 15 automatically prefetches layout components for dynamic routes, ensuring smooth navigation. However, dynamic content (like blog post data) is fetched on demand when the page is accessed.
Static Routes: Content remains the same for every user (e.g.,
/about
).Dynamic Routes: The content varies based on parameters (e.g.,
/blog/[slug]
).
Conclusion
Dynamic routes are a powerful feature in Next.js for rendering dynamic content. They allow you to build flexible applications and optimize user experience efficiently.