Nested Routes
Creating hierarchical URL structures in Next.js
🗂️ What are Nested Routes?
Nested routes allow you to create hierarchical URL structures by organizing folders inside the app directory. Each folder represents a URL segment, making it easy to build complex navigation patterns.
// Folder structure creates routes automatically
app/
blog/
page.js // /blog
[slug]/
page.js // /blog/my-post
Understanding Route Hierarchy
Next.js uses a file-system based router where folders define routes. Nested folders create nested URL paths, allowing you to organize your application logically with parent-child relationships between pages.
Folder Structure
Folders create URL segments
app/dashboard/settings/
→ /dashboard/settings
page.js Files
Make routes publicly accessible
app/about/page.js
→ /about route
Deep Nesting
Create multi-level hierarchies
app/shop/products/[id]/
→ /shop/products/123
Dynamic Segments
Use brackets for parameters
app/user/[id]/page.js
→ /user/42
🔹 Basic Nested Route Example
Create a simple blog with nested routes:
// app/blog/page.js
export default function BlogPage() {
return (
<div>
<h1>Blog Home</h1>
<p>Welcome to our blog!</p>
</div>
)
}
URL: /blog
Blog Home
Welcome to our blog!
🔹 Multi-Level Nesting
Build deeper route hierarchies for complex applications:
🔸 Folder Structure
app/
dashboard/
page.js → /dashboard
settings/
page.js → /dashboard/settings
profile/
page.js → /dashboard/settings/profile
// app/dashboard/settings/profile/page.js
export default function ProfilePage() {
return (
<div>
<h2>Profile Settings</h2>
<p>Update your profile information</p>
</div>
)
}
URL: /dashboard/settings/profile
Profile Settings
Update your profile information
🔹 Dynamic Nested Routes
Combine nested routes with dynamic segments:
🔸 Blog Post Example
// app/blog/[slug]/page.js
export default function BlogPost({ params }) {
return (
<div>
<h1>Post: {params.slug}</h1>
<p>Reading article about {params.slug}</p>
</div>
)
}
URL: /blog/nextjs-routing
Post: nextjs-routing
Reading article about nextjs-routing
🔹 Route Groups (Optional)
Organize routes without affecting the URL structure using parentheses:
Folder Structure:
app/
(marketing)/
about/page.js → /about
contact/page.js → /contact
(shop)/
products/page.js → /products
// app/(marketing)/about/page.js
export default function AboutPage() {
return <h1>About Us</h1>
}
// URL is /about (not /marketing/about)