1. Basic Concepts
app/ Directory
- New Next.js convention for colocating routes, layouts, and data.
- Every folder under
app/ becomes a route segment.
page.tsx
- Defines the UI for a specific route segment.
- Exported React component is rendered into nearest parent layout.
layout.tsx
- Provides shared UI (e.g. headers, footers) for all nested pages.
- Wraps its child
page.tsx (and any deeper layouts/pages).
2. Rendering at Root (/)
app/
├─ layout.tsx ← Root layout
└─ page.tsx ← Root page
- When visiting
/:
- Root
layout.tsx renders first (e.g. <html>, <body>, shared nav).
- Root
page.tsx renders inside the layout’s <main> (or wherever {children} is placed).
3. Nested Routes
app/
├─ layout.tsx
├─ page.tsx
└─ dashboard/
├─ layout.tsx
└─ page.tsx
- Visiting
/dashboard:
- Root
layout.tsx → provides global UI.
dashboard/layout.tsx → wraps dashboard-specific UI.
dashboard/page.tsx → renders page content.
4. Dynamic Segments
- Folder name with
[param] creates a dynamic route.
app/
└─ blog/
├─ [slug]/
│ ├─ layout.tsx
│ └─ page.tsx
- Requesting
/blog/hello-world:
slug = "hello-world" passed to both layout and page via props.
5. Special Files
loading.tsx
- Shown while a segment’s data is loading.
not-found.tsx
- Custom UI for 404 responses within a route segment.
- Rendered when no matching page or data is found.
- Can be placed alongside
page.tsx and layout.tsx to handle missing content at any nesting level.
error.tsx
- Error boundary for the segment.
route.ts
- Defines server-only request handlers for the segment.
- Export HTTP method functions (e.g.
export function GET(req), export function POST(req)) to handle API requests at that path.
- Supports
Cache-Control, middleware usage, and request/response streaming.
- Placed alongside
page.tsx or layout.tsx, it maps directly to the segment’s URL for API routes.