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/about5āāā blog/6ā āāā page.tsx ā yoursite.com/blog7āāā contact/8 āāā page.tsx ā yoursite.com/contactYour First Page
src/app/about/page.tsx
tsx
1// src/app/about/page.tsx2export 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 ā /blog4 āāā tutorials/5 āāā page.tsx ā /blog/tutorials6 āāā nextjs/7 āāā page.tsx ā /blog/tutorials/nextjsSpecial 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
⢠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