App Router Basics 🗺️
The App Router (Next.js 13+) turns directories into routes and gives you layout superpowers. Picture app/ as a tree: folders are branches, page.tsx leaves render UI.
Directory Anatomy 🌳
app/
├─ page.tsx → /
├─ about/
│ └─ page.tsx → /about
├─ products/
│ ├─ layout.tsx
│ └─ [id]/
│ └─ page.tsx → /products/123
└─ api/
└─ hello/
└─ route.ts → /api/hello- Each folder is a route segment.
page.tsx= entry point (must default export a component).
Dynamic Segments 🧩
app/products/[id]/page.tsx renders /products/:id.
export default function ProductPage({ params }: { params: { id: string } }) {
return <h1>Product {params.id}</h1>;
}Use [[...slug]] for optional catch-alls.
Nested Routes + Layouts 🧱
layout.tsxdefines shared UI for all child segments.- Layouts can fetch data server-side (async) and wrap children.
// app/dashboard/layout.tsx
export default function DashboardLayout({ children }) {
return (
<section>
<Sidebar />
<main>{children}</main>
</section>
);
}Templates 🧪
template.tsx behaves like layout but re-renders on navigation (great for per-page transitions or animations).
Route Groups (group) 📦
Folders wrapped in parentheses don’t affect the URL.
app/
├─ (marketing)/page.tsx → /
├─ (app)/dashboard/page.tsx → /dashboardUse groups to organize layouts or split concerns.
Parallel Routes 🛤️
- Define slots via folders starting with
@(e.g.,@modal,@feed). - Layout renders multiple
childrenprops, enabling multi-pane UIs.
Intercepting Routes 🚦
Bring another route’s UI into the current tree (modals over lists).
- Use folders like
(.)settingsor(..)loginto intercept sibling or parent routes. - Perfect for modals that show detail while keeping background context.
Route Handlers (API-like) 🧑🍳
app/api/hello/route.ts:
import { NextResponse } from 'next/server';
export async function GET() {
return NextResponse.json({ message: 'hi' });
}- Support HTTP verbs (
GET,POST, etc.). - Run on the server (Edge or Node depending on config).
Analogy: the App Router is a bonsai garden—you prune folders into the shapes (routes) you need, and layouts/templates are the bonsai wires guiding growth.
Once this mental model clicks, complex navigation (modals, split panes, streaming routes) becomes straightforward. ✨