Next js

Dynamic Routing In Next Js

What is Dynamic Routing?

  • Dynamic routing lets you create pages with variable paths.

  • Instead of hardcoding all URLs, you define dynamic segments that act as placeholders.

  • Perfect for URLs like /posts/1, /users/john, or /products/shoes.


How to Create Dynamic Routes?

  • Use square brackets in the filename inside the pages folder.

Example:

bash
pages/
├── posts/
│ └── [id].js
  • [id].js becomes a dynamic page where id is the variable part of the URL.


Accessing Dynamic Route Parameters

In the dynamic page, use useRouter or getStaticProps / getServerSideProps to access the parameter.

Example: pages/posts/[id].js

jsx
import { useRouter } from 'next/router';

export default function Post() {
const router = useRouter();
const { id } = router.query; // id from URL

return <h1>Post ID: {id}</h1>;
}


Dynamic Routes with Static Generation (getStaticPaths)

When using Static Site Generation (SSG) with dynamic routes, you need to specify which paths to pre-render.

Example:

jsx
export async function getStaticPaths() {
return {
paths: [
{ params: { id: '1' } },
{ params: { id: '2' } },
],
fallback: false, // show 404 for others
};
}

export async function getStaticProps({ params }) {
return {
props: {
id: params.id,
},
};
}

export default function Post({ id }) {
return <h1>Post ID: {id}</h1>;
}


Catch-All Routes

  • For nested or variable-length URLs, use [...param].js.

Example:

bash
pages/blog/[...slug].js
  • URL /blog/2025/08/02/title passes slug = ['2025', '08', '02', 'title'].


Summary

Feature How to Use
Dynamic Routes Use [param].js in pages/
Access Route Params useRouter or data fetching methods
Static Generation Paths Use getStaticPaths with params
Catch-All Routes Use [...param].js for nested paths

Leave a Reply

Your email address will not be published. Required fields are marked *