Next.js Nested Routes
Next.js provides a powerful file-based routing system. Nested routing is an extension of this system where you organize routes using folders inside folders.
This helps you build structured applications like blogs, dashboards, and e-commerce websites.
What are Nested Routes?
In Next.js:
Each file inside the
pages/directory becomes a routeNested routes are created using subfolders
Example:
pages/
├── index.js → /
├── about.js → /aboutNow if you create a folder:
pages/
├── nested/
│ ├── index.js → /nested
│ └── page.js → /nested/pageThis is called nested routing.
How Nested Routing Works
pages/is the rootEvery folder = part of URL
Every file = a route
You can create unlimited levels of nesting.
Step-by-Step Implementation
Step 1: Create Project
npx create-next-app my-appcd my-app
npm installStep 2: Create Nested Folder
Create a folder inside pages/:
pages/nested/Step 3: Create Root Page of Nested Route
// pages/nested/index.js
export default function Nested() {
return (
<div>
<h1>Nested Route Home</h1>
</div>
);
}Access:
http://localhost:3000/nestedStep 4: Create Child Page
// pages/nested/nested_page.js
export default function NestedPage() {
return (
<div>
<h1>Nested Page</h1>
</div>
);
}Access:
http://localhost:3000/nested/nested_pageReal Example: Blog Structure
Let’s understand with a real-world example.
Step 1: Create Home Page
// pages/index.js
export default function Home() {
return <h1>Home Page</h1>;
}Step 2: Create Articles Page
// pages/articles.js
export default function Articles() {
return <h1>Articles Page</h1>;
}Access:
/articlesStep 3: Create First Nested Route (Category)
pages/articles/dsa.jsexport default function DSA() {
return <h1>DSA Articles</h1>;
}Access:
/articles/dsaStep 4: Create Second Nested Route (Post)
pages/articles/dsa/post1.jsexport default function Post1() {
return <h1>Post 1</h1>;
}Access:
/articles/dsa/post1Final Folder Structure
pages/
├── index.js
├── articles.js
├── articles/
│ ├── dsa.js
│ └── dsa/
│ └── post1.jsKey Points to Remember
Folder name becomes part of URL
index.js = default route of folder
Nested folders = nested URLs
Easy to scale large applications
When to Use Nested Routes
Use nested routes when:
You have categories and subcategories
You are building blogs or CMS
You are creating dashboards (profile/settings)
You want clean URL structure
Final Summary
Nested routing in Next.js is simple and powerful. By organizing your files into folders, you can automatically create structured and scalable routes without any extra configuration.