#nextjs #routing #app-router #file-system

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 PathFile Path
/src/app/page.tsx
/dashboardsrc/app/dashboard/page.tsx
/settings/profilesrc/app/settings/profile/page.tsx

Activity: Create a new page at /about.

  1. Create folder src/app/about.
  2. 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

  1. Create a route for /products.
  2. Create a dynamic route for /products/[id].
  3. In the product page component, display β€œProduct ID: X” (where X is the ID from the URL).
  4. Visit /products/laptop to test it.

See you tomorrow for Layouts & Templates! πŸ“