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...
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).
Markdown files
Databases
External APIs
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
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).
Run the development server:
npm run dev
Navigate to /blog
→ Result: 404 Not Found (because the dynamic parameter slug
is required).
Navigate to /blog/first
→ Result: The page displays the slug first
.
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>
);
}
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]
).
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.