← Back to chapters
02beginner

File-Based Routing (App Router)

How folders become URLs. Pages, nested routes, and the app directory structure.

How File Routing Works

This is probably the most elegant thing about Next.js. Instead of writing route configurations (like you do with React Router), you just create folders and files. The file system IS your router.

šŸ’”

The rule is simple

A folder = a route segment. A 'page.tsx' inside that folder = a publicly accessible page. No page.tsx? That folder is just for organization.

Basic Routes

Folder → URL mapping
text
1src/app/
2ā”œā”€ā”€ page.tsx → yoursite.com/
3ā”œā”€ā”€ about/
4│ └── page.tsx → yoursite.com/about
5ā”œā”€ā”€ blog/
6│ └── page.tsx → yoursite.com/blog
7└── contact/
8 └── page.tsx → yoursite.com/contact

Your First Page

src/app/about/page.tsx
tsx
1// src/app/about/page.tsx
2export default function AboutPage() {
3return (
4 <div>
5 <h1>About Me</h1>
6 <p>I'm learning Next.js and it's awesome.</p>
7 </div>
8);
9}

That's literally it. Create the folder 'about', put a 'page.tsx' in it, export a default React component. Visit '/about' and there it is.

Nested Routes

Need deeper paths? Just nest folders:

Nested routes
text
1src/app/
2└── blog/
3 ā”œā”€ā”€ page.tsx → /blog
4 └── tutorials/
5 ā”œā”€ā”€ page.tsx → /blog/tutorials
6 └── nextjs/
7 └── page.tsx → /blog/tutorials/nextjs

Special Files

Next.js has special filenames that do specific things. Here are the ones you'll use:

FeatureWhat it doesWhen to use
page.tsxThe actual page contentRequired to make route accessible
layout.tsxWraps page + childrenPersists across navigations
loading.tsxLoading UI (Suspense)Shown while page loads
error.tsxError boundaryCatches errors gracefully
not-found.tsx404 pageCustom not found UI
šŸš€

Pro tip

You DON'T need to create all these files.
• Start with just page.tsx
• Add layout.tsx when you need shared UI
• Add loading.tsx when you need loading states
• Keep it simple, add files as needed

ā–¶Watch and Learn