Topic 5 of 39
File-Based Routing
Overview
Next.js uses a file-system based router. The folders you create inside the app/ directory define your URL paths. A folder becomes a route segment, and a page.tsx file inside it makes that route publicly accessible.
Syntax
bash
app/
├── page.tsx # Maps to: /
├── about/
│ └── page.tsx # Maps to: /about
└── contact/
└── page.tsx # Maps to: /contactCommon Pitfalls
- Creating a folder but forgetting to add a
page.tsxfile inside it (the route will result in a 404). - Using invalid file names for UI components; only reserved names like page, layout, loading, etc., have special routing meaning.
Interview Questions
Q:
How does routing in Next.js differ from traditional React apps using React Router?
A:
In traditional React, routing is configured programmatically via code (e.g., <Route> components). Next.js uses file-based routing where the folder structure dictates the URL paths.
Real-World Example
Creating a basic multi-page company website.
example
bash
// app/about/page.tsx
export default function AboutPage() {
return <h1>About Our Company</h1>;
}
// app/services/page.tsx
export default function ServicesPage() {
return <h1>Our Services</h1>;
}Check Your Knowledge
Test your understanding of File-Based Routing with these quick questions.