Day 2 β The App Router: File-System Routing
π§ Day 2 β The App Router: File-System Routing
Zero to Hero β Hands-on Next.js Tutorial
In Angular or classic React, you define routes in a config file (like app.routes.ts).
In Next.js, the File System IS the Router. π
Today, we learn how to create pages just by creating folders.
π¦ 1. Basic Routes
A Route is defined by a folder.
The UI for that route is defined by a page.tsx file inside that folder.
| URL Path | File Path |
|---|---|
/ | src/app/page.tsx |
/dashboard | src/app/dashboard/page.tsx |
/settings/profile | src/app/settings/profile/page.tsx |
Activity:
Create a new page at /about.
- Create folder
src/app/about. - Create file
src/app/about/page.tsx.
export default function AboutPage() {
return <h1>About Us</h1>;
}
Now visit http://localhost:3000/about. Easy!
π© 2. Dynamic Routes ([slug])
What if we want a blog post at /blog/1 or /blog/hello-world?
We use square brackets [folderName].
Create: src/app/blog/[slug]/page.tsx
export default function BlogPost({ params }: { params: { slug: string } }) {
return (
<div>
<h1>Blog Post: {params.slug}</h1>
</div>
);
}
Now visit:
http://localhost:3000/blog/nextjs-is-cool-> βBlog Post: nextjs-is-coolβhttp://localhost:3000/blog/123-> βBlog Post: 123β
The value inside the URL is passed as a prop!
π§ 3. Route Groups ((group))
Sometimes you want to organize files without changing the URL.
Wrap the folder name in parenthesis: (marketing).
src/app/(marketing)/about/page.tsx-> served at/about.src/app/(shop)/cart/page.tsx-> served at/cart.
This is useful for keeping your project organized or sharing different Layouts (more on that tomorrow!).
π₯ 4. Catch-all Segments ([...slug])
To capture everything after a path (e.g., /docs/a/b/c), use three dots: [...slug].
- File:
src/app/docs/[...slug]/page.tsx - URL:
/docs/getting-started/install - Params:
{ slug: ['getting-started', 'install'] }
π§ͺ Challenge: Day 2
- Create a route for
/products. - Create a dynamic route for
/products/[id]. - In the product page component, display βProduct ID: Xβ (where X is the ID from the URL).
- Visit
/products/laptopto test it.
See you tomorrow for Layouts & Templates! π