layout-templateEngineering

Next.js (App Router)

Server vs client components, file-based routing, data fetching, caching, and server actions on the App Router.

1 item

Links1

01NotesNote

Server Components are the default — and the big idea

In the App Router, components are Server Components unless you add "use client". Server Components run on the server only: they can fetch data directly (await a DB/API call right in the component), keep secrets server-side, and ship zero JavaScript to the browser for that part of the tree. Reach for a Client Component only when you need interactivity — state, effects, event handlers, browser APIs.

  • Push "use client" down to the leaves that actually need it. A whole page doesn't need to be client just because one button is interactive.
  • Server Components can import and render Client Components, but not the reverse. Pass server-fetched data down as props, or pass Server Components as children into a Client Component.

Routing

  • File-based: a folder under app/ with a page.tsx is a route. layout.tsx wraps a segment and its children (and persists across navigation). loading.tsx gives an instant Suspense fallback; error.tsx is a route-level error boundary.
  • Dynamic segments via [id], route groups via (group) for organization without affecting the URL.

Data fetching & caching

  • Fetch directly in Server Components. fetch is augmented with caching controls: cache by default, opt into dynamic with { cache: "no-store" }, or time-based revalidation with { next: { revalidate: 60 } }.
  • Use revalidatePath / revalidateTag to invalidate cached data after a mutation.
  • Wrap slow data in <Suspense> so the shell streams immediately and the slow part fills in — this is how you keep TTFB low.

Server Actions

  • "use server" functions let you mutate data from a form or event without writing an API route. Great for forms and simple mutations; they run on the server and can revalidate cache in the same call.
  • Still validate input inside the action (Zod) — a server action is a public endpoint.

Gotchas

  • Don't reach for useEffect + client fetch out of habit — if the data can be fetched on the server, do it there.
  • Environment variables: only NEXT_PUBLIC_* are exposed to the browser. Keep secrets unprefixed.
  • Hydration mismatches come from rendering different output on server vs client (e.g. Date.now(), window); guard browser-only code.
Next.js (App Router) — Maqbool Thoufeeq Tharayil