Overview

Next.js App Router uses a file-based routing system where the file structure in the app directory directly maps to URL routes. This approach simplifies routing configuration and provides better performance through automatic code splitting.

Route Segments

Each folder in the app directory represents a route segment:
app/
├── page.tsx          # / (root route)
├── about/
│   └── page.tsx      # /about
├── blog/
│   ├── page.tsx      # /blog
│   └── [slug]/
│       └── page.tsx  # /blog/[slug] (dynamic route)
└── dashboard/
    ├── page.tsx      # /dashboard
    └── settings/
        └── page.tsx  # /dashboard/settings

Essential Special Files

page.tsx

  • Makes a route publicly accessible
  • Required for a route to be accessible
  • Defines the UI for that route

layout.tsx

  • Shared UI for multiple pages
  • Wraps child layouts and pages
  • Maintains state during navigation

loading.tsx

  • Loading UI for a route segment
  • Shows while page is loading
  • Automatically wraps page and children

not-found.tsx

  • 404 page for a route segment
  • Shows when route is not found
  • Can be nested at different levels

Basic Navigation

import Link from "next/link";

export default function Navigation() {
  return (
    <nav>
      <Link href="/">Home</Link>
      <Link href="/about">About</Link>
      <Link href="/blog/hello-world">Blog Post</Link>
    </nav>
  );
}

Programmatic Navigation

"use client";

import { useRouter } from "next/navigation";

export default function MyComponent() {
  const router = useRouter();

  const handleClick = () => {
    router.push("/dashboard");
    // or
    router.replace("/login");
    // or
    router.back();
  };

  return <button onClick={handleClick}>Navigate</button>;
}

Basic Route Organization

Simple Structure

app/
├── layout.tsx            # Root layout
├── page.tsx              # Home page
├── about/
│   └── page.tsx          # About page
└── contact/
    └── page.tsx          # Contact page

Nested Routes

app/
├── layout.tsx            # Root layout
├── page.tsx              # Home page
└── dashboard/
    ├── layout.tsx        # Dashboard layout
    ├── page.tsx          # /dashboard
    └── settings/
        └── page.tsx      # /dashboard/settings
Key Takeaway: Next.js file-based routing simplifies route management by using the file system structure to define routes. Start with basic page.tsx and layout.tsx files, then add loading.tsx and not-found.tsx as needed.