🟢 Static Rendering default
Rendered ahead of time and reused. Best for content that's the same for everyone — marketing pages, blog posts, docs. Add revalidate for ISR (rebuild in the background on a schedule).
Next.js stopped being "React with routing" and became a full-stack framework built on React Server Components. The App Router changed the defaults: components render on the server, data is fetched where it's used, and caching happens on four different layers. Getting Next.js right today is mostly about understanding those defaults — and knowing when to opt out.
"use client" only at the interactive leaves. Most Next.js mistakes are fighting that grain instead of working with it.Routing is defined by the folder structure under app/. Special files have reserved meanings — you compose a route from them rather than wiring routing by hand.
| File | Role |
|---|---|
page.tsx | The unique UI of a route (makes the segment publicly routable). |
layout.tsx | Shared UI that wraps children and persists across navigation (no re-render). |
loading.tsx | Instant loading UI — a Suspense fallback shown while the segment streams. |
error.tsx | Error boundary for the segment (a Client Component). |
not-found.tsx | UI for notFound() and unmatched routes. |
route.ts | A Route Handler — an HTTP API endpoint (GET/POST…) instead of a page. |
app/
layout.tsx // root layout (required): <html><body>
page.tsx // route: /
blog/
layout.tsx // wraps every /blog/* route
page.tsx // route: /blog
[slug]/
page.tsx // dynamic route: /blog/:slug
loading.tsx // streamed fallback for the post
api/
revalidate/
route.ts // POST /api/revalidate
(marketing) to organise routes without affecting the URL. @slot folders enable parallel routes (render multiple pages in one layout) and (.) prefixes enable intercepting routes (e.g. a modal that has its own URL). Reach for these only when you need them.This is the single most important concept. Components are Server Components by default: they run only on the server, can be async, can talk to your database directly, and ship zero JavaScript to the browser. Adding "use client" at the top of a file opts that component (and its imports) into the client bundle so it can be interactive.
| Server Component | Client Component | |
|---|---|---|
| Default? | Yes | Opt in with "use client" |
| Can fetch data / hit DB | Yes, directly (async) | No — via API or props |
Hooks (useState, useEffect) | No | Yes |
| Event handlers / interactivity | No | Yes (onClick…) |
| Ships JS to browser | No | Yes |
Access secrets / process.env | Yes (safe) | Only NEXT_PUBLIC_* |
"use client" to the leaves. Don't mark a whole page as client just because one button needs onClick. Keep the page a Server Component and extract the interactive bit into its own small client component. Server Components can freely render client ones; you can also pass a Server Component as a child into a client component to keep it out of the bundle.You fetch data in the component that needs it — usually an async Server Component calling fetch() or your DB. Next dedupes identical requests in one render (request memoization), so you don't need to hoist fetching or prop-drill.
// app/blog/[slug]/page.tsx — a Server Component fetching its own data
export default async function Post({ params }) {
const { slug } = await params; // Next 15: params is async
const post = await fetch(`https://api/posts/${slug}`, {
next: { revalidate: 3600 }, // ISR: re-cache hourly
}).then(r => r.json());
return <article>{post.title}</article>;
}
Next.js caches on four distinct layers — knowing which one you're touching is what makes caching predictable:
| Layer | What it caches | Invalidate with |
|---|---|---|
| Request Memoization | Duplicate fetches within one render pass | Automatic (per request) |
| Data Cache | fetch results across requests & deploys | revalidateTag / revalidatePath / time |
| Full Route Cache | Rendered HTML/RSC payload of static routes | Redeploy or data-cache revalidation |
| Router Cache | Visited route segments, client-side | Navigation / router.refresh() |
fetch was cached by default. Next 15 flipped this: fetch, GET Route Handlers, and the client Router Cache are uncached by default — you opt into caching with cache: 'force-cache' or next: { revalidate }. Never assume; verify against the version in your package.json.A route is statically rendered (at build time, cached, fast) unless something forces dynamic rendering (per request). You rarely choose explicitly — using a dynamic API opts the route in automatically.
Rendered ahead of time and reused. Best for content that's the same for everyone — marketing pages, blog posts, docs. Add revalidate for ISR (rebuild in the background on a schedule).
Triggered when you use request-time data: cookies(), headers(), searchParams, or an uncached fetch. Use for personalised or always-fresh pages — dashboards, authenticated views.
Wrap a slow part in <Suspense> (or add loading.tsx) to send the fast shell immediately and stream the slow chunk when ready — better perceived performance without going fully dynamic.
// Send the page shell now; stream the slow feed when it resolves
import { Suspense } from "react";
export default function Page() {
return (
<>
<Header /> // instant
<Suspense fallback={<Skeleton />}>
<SlowFeed /> // streams in when ready
</Suspense>
</>
);
}
For writes, Server Actions replace hand-rolled API routes for most cases. A function marked "use server" runs on the server but can be called directly from a form or a client component — with progressive enhancement, so forms work before JS loads.
// app/actions.ts
"use server";
import { revalidatePath } from "next/cache";
export async function addComment(formData) {
const text = formData.get("text");
await db.comments.insert({ text }); // runs on server, secrets safe
revalidatePath("/post"); // refresh cached data
}
// in a Server Component — no client JS, no API route needed:
<form action={addComment}><input name="text" /></form>
next/imageUse it for all images: automatic resizing, modern formats, and lazy loading. Always set width/height (or fill) so the browser reserves space and avoids layout shift (CLS). Mark the above-the-fold hero priority.
next/fontSelf-hosts fonts at build time — no external request, no layout shift. If you can, prefer a system font stack and skip web fonts entirely for the fastest first paint.
Keep the client bundle small: minimise "use client", dynamic()-import heavy client-only widgets, and lean on Server Components so most rendering ships no JS at all.
server-only package to a module to make an accidental client import fail at build.NEXT_PUBLIC_* reach the browser. Everything else is server-only — keep API keys unprefixed.metadata or generateMetadata() per route instead of hand-writing <head> tags.process.env.API_KEY into a Client Component can bundle that value into the browser. Prefix browser-safe values with NEXT_PUBLIC_ deliberately, and guard server modules with import "server-only" so the mistake breaks the build instead of shipping.| Pitfall | Why it hurts | Instead |
|---|---|---|
"use client" at the top of the tree | Turns the whole subtree into client JS; loses RSC benefits | Mark only the interactive leaf components |
useEffect + fetch for initial data | Client waterfall, no SSR data, worse LCP | Fetch in an async Server Component |
Sequential awaits | Request waterfall — each waits for the last | Promise.all to parallelise independent fetches |
| Assuming the old caching default | Stale (or uncached) data after a version bump | Set cache/revalidate explicitly |
| Unauthenticated Server Actions | A public endpoint anyone can call | Auth + validate inside every action |
<img> instead of next/image | Layout shift, oversized downloads | next/image with dimensions |
A /products/[id] page shows product details (cacheable, same for everyone) plus a live stock count (per-request) and an interactive "add to cart" button. The best-practice split uses all three ideas at once.
// page.tsx — Server Component; product is cached, stock streams in
export default async function ProductPage({ params }) {
const { id } = await params;
const product = await getProduct(id); // cached (force-cache)
return (
<>
<ProductInfo product={product} /> // static, no JS
<Suspense fallback={<StockSkeleton />}>
<LiveStock id={id} /> // dynamic, streamed
</Suspense>
<AddToCart id={id} /> // client leaf
</>
);
}
"use client"; // this file only
export function AddToCart({ id }) {
const [pending, start] = useTransition();
return <button onClick={() => start(() => addToCart(id))}>
{pending ? "Adding…" : "Add to cart"}
</button>;
}
"use server";
export async function addToCart(id) {
const user = await requireSession(); // auth inside the action
await db.cart.add(user.id, id);
revalidateTag("cart");
}
| Question | Short answer |
|---|---|
| Default component type? | Server Component — add "use client" only for interactivity. |
| Where to fetch data? | In the async Server Component that needs it; memoization dedupes. |
| What triggers dynamic rendering? | cookies(), headers(), searchParams, or an uncached fetch. |
| Periodic rebuild (ISR)? | next: { revalidate: N } on the fetch or segment. |
| How to do writes? | Server Actions ("use server") — auth & validate inside. |
| Invalidate cached data? | revalidatePath / revalidateTag. |
| Faster perceived load? | <Suspense> / loading.tsx to stream. |
| Browser-exposed env var? | Prefix with NEXT_PUBLIC_ (only these leak). |
| Images & fonts? | next/image (with dimensions) and next/font. |
Six questions. Pick an answer for each, then check your score.
REST vs GraphQL vs gRPC — how the data your Server Components fetch is exposed.
Schemas & resolvers — if your Next.js data layer speaks GraphQL.
The backend it calls — capacity, retries & idempotency.
The hub — LLMs, agents, data & infra.