File-based Routing

Back

Loading concept...

πŸ—ΊοΈ Next.js File-based Routing: Your App’s GPS System

The Big Idea: Folders = Roads in Your App

Imagine your favorite pizza place. When you walk in, there are clear signs:

  • β€œOrder Here” β†’ takes you to the counter
  • β€œPick Up” β†’ takes you to get your food
  • β€œRestrooms” β†’ you know where that goes!

Next.js routing works exactly like this. Your folders are the signs, and your files are the destinations. No complicated setup neededβ€”just create a folder, and boom, you have a new page!


🏠 Pages and Routes: Building Your First Rooms

What’s a Route?

A route is just a path in your website’s address bar. Like:

  • mysite.com/ β†’ Home
  • mysite.com/about β†’ About page
  • mysite.com/contact β†’ Contact page

How Next.js Makes This Easy

In Next.js (App Router), you create routes by making folders inside the app folder:

app/
β”œβ”€β”€ page.tsx      β†’ mysite.com/
β”œβ”€β”€ about/
β”‚   └── page.tsx  β†’ mysite.com/about
└── contact/
    └── page.tsx  β†’ mysite.com/contact

That’s it! Folder name = URL path. Simple as pizza!

Real Example

Want a blog section? Just create:

app/
└── blog/
    └── page.tsx

Now mysite.com/blog works automatically. Magic? Nopeβ€”just smart design!


πŸ“„ Page Component: The Star of Every Route

What Makes a Page Special?

Every route needs one special file called page.tsx (or page.js). This file is like the welcome mat for that routeβ€”it’s what visitors see first.

Your First Page Component

// app/about/page.tsx

export default function AboutPage() {
  return (
    <div>
      <h1>About Us</h1>
      <p>We make awesome apps!</p>
    </div>
  );
}

The Secret Rules

  1. Must be named page.tsx - Other names won’t work
  2. Must export a default function - This is your component
  3. One per folder - Each route gets one page

Think of it like a house: each room (folder) can only have one front door (page.tsx).


🎭 Dynamic Routes: One Template, Many Pages

The Problem

Imagine you have 1000 products. Do you create 1000 folders?

  • app/product-1/page.tsx
  • app/product-2/page.tsx
  • … (yikes!)

NO WAY! That’s crazy talk!

The Solution: Square Brackets

Use [squareBrackets] to create a flexible route:

app/
└── products/
    └── [id]/
        └── page.tsx

Now ONE file handles:

  • mysite.com/products/1
  • mysite.com/products/999
  • mysite.com/products/cool-sneakers

Getting the Dynamic Value

// app/products/[id]/page.tsx

export default function ProductPage({
  params
}: {
  params: { id: string }
}) {
  return (
    <h1>Product: {params.id}</h1>
  );
}

Visit /products/42 β†’ Shows β€œProduct: 42” Visit /products/pizza β†’ Shows β€œProduct: pizza”

One file. Infinite possibilities! πŸš€


🎣 Catch-all Routes: The Super Net

When Dynamic Routes Aren’t Enough

What if your URL has multiple parts?

  • /docs/getting-started
  • /docs/api/hooks/useState
  • /docs/advanced/patterns/context/deep-dive

Each has a different number of segments. Dynamic routes can’t handle this alone.

Enter the Triple Dot: [...slug]

app/
└── docs/
    └── [...slug]/
        └── page.tsx

The ... is like a fishing netβ€”it catches EVERYTHING after /docs/.

How It Works

// app/docs/[...slug]/page.tsx

export default function DocsPage({
  params
}: {
  params: { slug: string[] }
}) {
  // slug is an ARRAY of all segments
  return (
    <div>
      <p>Path: {params.slug.join(' β†’ ')}</p>
    </div>
  );
}
URL params.slug
/docs/intro ['intro']
/docs/api/auth ['api', 'auth']
/docs/a/b/c/d ['a','b','c','d']

⚠️ Important Catch

/docs alone won’t work with [...slug]. You need at least ONE segment after /docs.


🎯 Optional Catch-all Routes: The Friendly Net

The Problem with Catch-all

Remember: /docs alone doesn’t work with [...slug].

But what if you WANT /docs to also show something?

The Solution: Double Brackets [[...slug]]

app/
└── docs/
    └── [[...slug]]/
        └── page.tsx

The extra brackets make the catch-all optional.

Now Everything Works!

// app/docs/[[...slug]]/page.tsx

export default function DocsPage({
  params
}: {
  params: { slug?: string[] }
}) {
  if (!params.slug) {
    return <h1>Welcome to Docs!</h1>;
  }

  return (
    <h1>Reading: {params.slug.join('/')}</h1>
  );
}
URL params.slug
/docs undefined
/docs/intro ['intro']
/docs/api/hooks ['api', 'hooks']

Best of both worlds! πŸŽ‰


πŸ“ Route Groups: The Invisible Organizers

The Messy Problem

Your app grows. Files everywhere:

app/
β”œβ”€β”€ login/
β”œβ”€β”€ register/
β”œβ”€β”€ forgot-password/
β”œβ”€β”€ dashboard/
β”œβ”€β”€ settings/
β”œβ”€β”€ profile/
└── ...20 more folders

Chaos! You want to organize these, but folders change URLs…

The Magic Parentheses: (groupName)

Folders with parentheses () are invisible in the URL!

app/
β”œβ”€β”€ (auth)/
β”‚   β”œβ”€β”€ login/
β”‚   β”‚   └── page.tsx    β†’ /login
β”‚   β”œβ”€β”€ register/
β”‚   β”‚   └── page.tsx    β†’ /register
β”‚   └── forgot-password/
β”‚       └── page.tsx    β†’ /forgot-password
β”‚
└── (dashboard)/
    β”œβ”€β”€ settings/
    β”‚   └── page.tsx    β†’ /settings
    └── profile/
        └── page.tsx    β†’ /profile

Why This is Awesome

  1. Organization - Related pages grouped together
  2. Shared Layouts - Each group can have its own layout
  3. Clean URLs - (auth) doesn’t appear in the address bar

Shared Layout Example

// app/(auth)/layout.tsx
// This layout wraps login, register, forgot-password

export default function AuthLayout({
  children
}: {
  children: React.ReactNode
}) {
  return (
    <div className="auth-container">
      <img src="/logo.png" alt="Logo" />
      {children}
    </div>
  );
}

All auth pages now share the same logo and containerβ€”without affecting their URLs!


πŸ—ΊοΈ The Complete Picture

graph TD A["app/"] --> B["page.tsx"] A --> C["about/"] C --> D["page.tsx"] A --> E["[id]/"] E --> F["page.tsx"] A --> G["[...slug]/"] G --> H["page.tsx"] A --> I["[[...opt]]/"] I --> J["page.tsx"] A --> K["&#35;40;group&#35;41;/"] K --> L["route/"] L --> M["page.tsx"] B --> B1["/"] D --> D1["/about"] F --> F1["/123, /abc"] H --> H1["/a/b/c"] J --> J1["/ or /x/y"] M --> M1["/route"]

πŸŽ“ Quick Reference

Pattern Folder Name Example URL Use Case
Static about/ /about Fixed pages
Dynamic [id]/ /products/42 Single variable
Catch-all [...slug]/ /docs/a/b/c Multiple segments
Optional [[...slug]]/ /docs or /docs/a/b Optional segments
Group (admin)/ URL unchanged Organization only

πŸš€ You Did It!

You now understand Next.js file-based routing like a pro:

  1. Folders = URLs - Simple and intuitive
  2. page.tsx = Content - The welcome mat for each route
  3. [brackets] = Dynamic values
  4. […spread] = Catch multiple segments
  5. [[…optional]] = Catch OR skip
  6. (parentheses) = Invisible organization

The beauty of Next.js routing? Your file structure IS your sitemap. No config files. No router setup. Just folders and files, working together like a well-organized library.

Now go build something amazing! 🎨✨

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.