Dynamic routes in Next.js allow you to create pages that vary based on URL parameters. They are typically used for detail pages such as blog posts, user profiles, or product pages.
Dynamic Routing:
Pages are created using a [param]
folder or file naming convention (e.g., app/blog/[id]/page.tsx
), where the dynamic segment (id
) is automatically parsed from the URL.
Data Fetching Options:
You can fetch data either on the server or on the client side. This means you can combine dynamic routing with Server Component fetch or Client Component fetch methods, depending on your requirements.
Using params
:
The dynamic value is passed into your component through a params
prop in Server Components or extracted using useParams()
in Client Components.
Server Component Example
The following example demonstrates a Server Component that fetches data based on a dynamic URL parameter:
// app/blog/[id]/page.tsx
interface BlogPostProps {
params: { id: string };
}
export default async function BlogPost({ params }: BlogPostProps) {
// Fetch data based on the dynamic ID from the URL.
const res = await fetch(`https://api.example.com/post/${params.id}`);
const data = await res.json();
return (
<article>
<h1>Post ID: {params.id}</h1>
<p>{data.content}</p>
</article>
);
}
Client Component Example
If the page needs to be interactive, you can use a Client Component with useParams()
:
"use client";
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
export default function BlogPost() {
const { id } = useParams();
const [data, setData] = useState(null);
useEffect(() => {
async function fetchData() {
const res = await fetch(`https://api.example.com/post/${id}`);
const result = await res.json();
setData(result);
}
if (id) fetchData();
}, [id]);
if (!data) return <p>Loading...</p>;
return (
<article>
<h1>Post ID: {id}</h1>
<p>{data.content}</p>
</article>
);
}
Per-URL Content:
Use dynamic routes when you need each URL to represent unique content, such as a blog post, product detail, or user profile.
SEO Benefits:
Server-rendered dynamic routes are beneficial for SEO because each page is pre-rendered with its respective content.
Static vs. Interactive Pages:
params
is preferred.useParams()
.