Next.js App Router 🚏
Next.js App Router (introduced in 13, matured by 15+) embraces React Server Components, segment-based layouts, and streaming-first rendering.
1) App Router Concepts 🧭
- Layouts:
app/(marketing)/layout.tsxdefines persistent UI for nested routes. - Nested routes: directory structure mirrors route nesting (
app/dashboard/settings/page.tsx). - Loading/Error boundaries:
loading.tsxacts as Suspense fallback per segment;error.tsxwraps failures.global-error.tsxhandles root-level crashes. - Route groups:
(group)directories organize files without affecting URL structure.
🧱 Think in segments: each folder can own layout, loading, error, and route-specific metadata.
2) Server Components by Default ⚛️
- Files under
app/are server components unless marked with"use client". - Server components can fetch data, access secrets, and import server-only modules.
- Insert client components for interactivity: place
"use client"at file top, then render inside server component.
"use client";
export function ThemeToggle() {
const [theme, setTheme] = useTheme();
return <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>Toggle</button>;
}3) Data Fetching, Caching, Streaming 🌐
- Use the native
fetchin server components; Next.js caches GET requests by default. - Control caching with
fetch(url, { cache: "no-store" })orrevalidate: 60. generateStaticParams+ segment revalidation enable incremental static regeneration.- Streaming: server sends layout shell immediately, nested segments stream as they resolve; pairs with
loading.tsxfor skeletons.
4) Revalidation & Mutations 🔄
revalidateTag+revalidatePathschedules cache invalidation after mutations (e.g., form actions).- Route Handlers (
app/api/users/route.ts) let you build serverless endpoints reusing the same server runtime.
5) React Version Handling 🧩
- App Router requires React 18+ and tracks React 19.x quickly; features like actions,
useFormStatus,useOptimistic, anduse()align with React versions bundled by Next.js. - Pages Router (legacy) still supports React 17 patterns but lacks RSC features; ensure dependencies support the router mode you target.
Key Takeaways ✅
- Organize routes with layouts, loading/error files, and route groups for clarity.
- Server components are default; use
"use client"to opt into client-side interactivity. - Built-in caching, streaming, and revalidation reduce boilerplate.
- Keep Next.js + React versions in sync to access the latest App Router capabilities.
Recap 🔄
Next.js App Router pairs React Server Components with layouts, Suspense-driven loading, and data caching. Structure routes via folders, fetch data on the server, sprinkle client components for interactivity, and leverage revalidation APIs to keep content fresh.
Last updated on