0
0
NextjsHow-ToBeginner · 3 min read

How to Create Nested Routes in Next.js: Simple Guide

In Next.js, create nested routes by organizing files inside folders within the app directory. Each folder represents a route segment, and placing a page.js file inside creates a nested route automatically.
📐

Syntax

Next.js uses the app folder to define routes. Each folder inside app is a route segment. Inside these folders, a page.js file defines the page component for that route.

For nested routes, create folders inside folders. For example, app/dashboard/settings/page.js creates a nested route at /dashboard/settings.

plaintext
app/
  page.js          // Route: /
  dashboard/
    page.js        // Route: /dashboard
    settings/
      page.js      // Route: /dashboard/settings
💻

Example

This example shows a simple nested route structure with a home page, a dashboard page, and a nested settings page inside the dashboard.

javascript
app/
  page.js
  dashboard/
    page.js
    settings/
      page.js

// app/page.js
export default function HomePage() {
  return <h1>Home Page</h1>;
}

// app/dashboard/page.js
export default function DashboardPage() {
  return <h1>Dashboard</h1>;
}

// app/dashboard/settings/page.js
export default function SettingsPage() {
  return <h1>Settings</h1>;
}
Output
<h1>Home Page</h1> at /, <h1>Dashboard</h1> at /dashboard, <h1>Settings</h1> at /dashboard/settings
⚠️

Common Pitfalls

  • Forgetting to add page.js inside nested folders means no route is created.
  • Using the old pages folder instead of app for nested routes misses new App Router features.
  • Not restarting the dev server after adding new folders can cause routes not to appear immediately.
plaintext
/* Wrong: Missing page.js in nested folder */
app/
  dashboard/
    settings/
      // no page.js here - no route created for /dashboard/settings

/* Right: Add page.js */
app/
  dashboard/
    settings/
      page.js  // route works now
📊

Quick Reference

Remember these tips for nested routes in Next.js:

  • Each folder inside app is a route segment.
  • Place a page.js file inside folders to create routes.
  • Nested folders create nested routes automatically.
  • Use layout.js files for shared UI in nested routes.

Key Takeaways

Create nested routes by placing folders inside the app directory with page.js files.
Each folder represents a part of the URL path, building nested routes naturally.
Always include a page.js file inside nested folders to activate the route.
Use layout.js files to share UI across nested routes.
Restart the dev server if new routes do not appear immediately.