Overview

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.

Core Concepts

Example

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>
  );
}

When to Use