Next.js Tutorial
- Next.js Introduction
- Next.js Installation
- Project Structure
- Pages & Routing
- Dynamic Routing
- Linking & Navigating
- Data Fetching (SSR)
- Data Fetching (SSG)
- Client-Side Rendering
- API Routes
- Layouts & Components
- Styling
- Image Optimization
- Font Optimization
- Script Optimization
- Middleware
- Environment Variables
- Error Handling
- Authentication
- React Server Components
- Server Actions
- Suspense & Streaming
- Caching & Revalidation
- TypeScript Integration
- Deployment
Pages & Routing
In standard React applications, developers use react-router-dom and define all application routes inside a root Component using <Route path="..." /> syntax.
Next.js handles routing completely differently. It uses a File-System Based Router. This means that simply creating a file automatically creates a corresponding URL route in your application. No complex configurations needed!
Pages Router Routing
In the classic Pages Router, any `.js` or `.tsx` file inside the pages/ directory becomes a route instantly.
pages/
├── index.js --> Route: /
├── about.js --> Route: /about
└── blog/
├── index.js --> Route: /blog
└── first-post.js--> Route: /blog/first-post
To create the /about page, you simply write:
// pages/about.js
export default function About() {
return <h1>About Us</h1>
}
App Router Routing
In Next.js 13+, the App Router (app/ directory) handles routing using folders. A folder defines the route path, and a particular file named page.js (or page.tsx) creates the UI for that route.
app/
├── page.js --> Route: /
├── about/
│ └── page.js --> Route: /about
└── blog/
├── page.js --> Route: /blog
└── first-post/
└── page.js --> Route: /blog/first-post
Inside page.js, you simply export a default component, exactly like before:
// app/about/page.js
export default function AboutPage() {
return <h1>The About Route in the App Directory</h1>;
}
Nested Routes
Nested routing allows you to create hierarchical UI components. Next.js supports deeply nested routes just by deeply nesting your folders or files.
For example, if you want a user dashboard displaying settings, you could have:
app/dashboard/page.js->/dashboardapp/dashboard/settings/page.js->/dashboard/settings
Layouts & Special Files (App Router)
In addition to page.js, the App router features other special file names that wrap your pages:
- layout.js: Shared UI for a segment and its children (e.g. Navbars/Sidebars).
- loading.js: Loading UI shown while data fetching occurs.
- error.js: Error UI displayed when something crashes in the component tree.
- not-found.js: Custom 404 UI.
Conclusion
File-system routing is one of Next.js's most powerful features. It forces you to maintain an intuitive, highly structured codebase. But what happens when your routes need to change based on a database ID, like /users/123? Next, we will cover Dynamic Routing.