Next.js App Router
Overview
Build features the App Router way: server components by default, client
components only when needed, and colocated routes under app/.
Process
- Add a route by creating
app/<segment>/page.tsx; addlayout.tsxfor shared UI andloading.tsx/error.tsxfor states. - Keep components as React Server Components unless they need state, effects, or
browser APIs. Add
"use client"only to those leaf components. - Fetch data in server components with
async/await; avoid client-side fetching for initial render when the server can do it. - Put API endpoints in
app/api/<name>/route.tsusing the WebRequest/ResponseAPIs. - Verify with
npm run build(catches server/client boundary and type errors).
Data Fetching
- Prefer
fetchin Server Components with Next.js caching options (cache,next.revalidate) documented in code comments when non-default. - Use
loading.tsxfor slow segments; avoid blocking the entire page. - Mutations: Server Actions or Route Handlers — validate input server-side.
Route Handlers
- Export named HTTP functions (
GET,POST, …) fromroute.ts. - Return
Response.json()with correct status codes. - Never import client-only modules into
route.ts.
Guidelines
- Never import server-only modules (fs, secrets, DB clients) into client components.
- Read secrets from environment variables on the server only; never expose them
via
NEXT_PUBLIC_*unless they are truly public. - Keep
page.tsxthin; move logic into small, typed functions undersrc/or colocatedlib/. - Prefer
next/linkandnext/imageover raw anchors/images. - Colocate tests for pure helpers; run
npm run buildbefore claiming done.
Deployment
See the shared deploy-vercel skill when shipping to Vercel.
Anti-patterns
- Marking entire pages
"use client"to avoid thinking about server boundaries. - Fetching secrets or private APIs from the browser.
- Giant
page.tsxfiles mixing UI, data access, and validation.


