Topic 2 of 47
File-Based Routing
Overview
Next.js uses the file system as the router — the folder/file structure in app/ directly maps to URL paths. This eliminates the need for a router configuration file and co-locates route code with its URL.
Syntax
bash
app/
├── page.tsx → /
├── layout.tsx → root layout (wraps everything)
├── loading.tsx → automatic Suspense loading UI
├── error.tsx → error boundary for this segment
├── not-found.tsx → 404 page
├── blog/
│ ├── page.tsx → /blog
│ └── [slug]/
│ └── page.tsx → /blog/any-post-slug
├── dashboard/
│ ├── layout.tsx → dashboard-specific layout
│ ├── page.tsx → /dashboard
│ └── settings/
│ └── page.tsx → /dashboard/settings
└── api/
└── users/
└── route.ts → /api/users (API endpoint)Common Pitfalls
- Dynamic routes with [...slug] (catch-all) vs [[...slug]] (optional catch-all) behave differently — the optional one also matches the root.
- Route groups (folder) allow organizing routes without affecting the URL structure.
- Interview tip: In Next.js, a layout.tsx wraps child pages and persists across navigation (doesn't unmount) — unlike page.tsx which replaces on every navigation.
Real-World Example
Route groups and parallel routes for a dashboard layout:
example
bash
app/
├── (marketing)/ ← route group (no URL segment)
│ ├── page.tsx → /
│ ├── about/page.tsx → /about
│ └── layout.tsx → marketing layout (navbar, footer)
│
├── (dashboard)/ ← different layout, same URL depth
│ ├── layout.tsx → dashboard layout (sidebar)
│ ├── overview/page.tsx → /overview
│ └── analytics/
│ ├── page.tsx → /analytics
│ └── [period]/
│ └── page.tsx → /analytics/monthly, /analytics/weekly
│
└── @modal/ ← parallel route (shown simultaneously)
└── page.tsx → renders alongside main content