← All tutorials
Next.js Best Practices

Next.js best practices

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.

The mental shift. In the App Router everything is a Server Component until you say otherwise. Fetch data on the server, keep secrets on the server, ship as little JavaScript as possible, and add "use client" only at the interactive leaves. Most Next.js mistakes are fighting that grain instead of working with it.

Foundations  The App Router & file conventions

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.

FileRole
page.tsxThe unique UI of a route (makes the segment publicly routable).
layout.tsxShared UI that wraps children and persists across navigation (no re-render).
loading.tsxInstant loading UI — a Suspense fallback shown while the segment streams.
error.tsxError boundary for the segment (a Client Component).
not-found.tsxUI for notFound() and unmatched routes.
route.tsA 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
Route groups & more: wrap a folder in parentheses (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.

The core model  Server vs Client Components

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 and Client Components in one tree A server component tree renders on the server; small client component leaves marked use client are hydrated in the browser for interactivity. layout (server)no JS shipped page (server, async)fetches data directly ProductList (server) "use client" AddToCart 🖱️ "use client" SearchBox 🔎
Server ComponentClient Component
Default?YesOpt in with "use client"
Can fetch data / hit DBYes, directly (async)No — via API or props
Hooks (useState, useEffect)NoYes
Event handlers / interactivityNoYes (onClick…)
Ships JS to browserNoYes
Access secrets / process.envYes (safe)Only NEXT_PUBLIC_*
Push "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.

Data  Fetching & the caching layers

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:

LayerWhat it cachesInvalidate with
Request MemoizationDuplicate fetches within one render passAutomatic (per request)
Data Cachefetch results across requests & deploysrevalidateTag / revalidatePath / time
Full Route CacheRendered HTML/RSC payload of static routesRedeploy or data-cache revalidation
Router CacheVisited route segments, client-sideNavigation / router.refresh()
Caching defaults changed — check your version. In Next 14, 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.

Rendering  Static, dynamic, streaming

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.

🟢 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).

🟠 Dynamic Rendering

Triggered when you use request-time data: cookies(), headers(), searchParams, or an uncached fetch. Use for personalised or always-fresh pages — dashboards, authenticated views.

🔵 Streaming with Suspense

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>
    </>
  );
}
Partial Prerendering (PPR) is the emerging best-of-both: a static shell served instantly with dynamic "holes" streamed in, in one response. It's still experimental — know it's coming, but don't build production on it until it's stable in your version.

Mutations  Server Actions

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>
Server Actions are public HTTP endpoints. Anyone can invoke one — so always authenticate and validate inside the action, exactly as you would an API route. Never trust the caller; check the session and validate the input (e.g. with Zod) before touching data.

Speed  Performance best practices

🖼️ next/image

Use 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/font

Self-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.

📦 Ship less JavaScript

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.

Measure, don't guess. Watch the Core Web Vitals (LCP, INP, CLS) with the built-in analytics or Lighthouse. The framework gives you fast defaults; regressions almost always come from a large client bundle or an unoptimised image — both visible in the build output and a trace.

Conventions  Project structure that scales

  • Colocate components, tests, and helpers next to the route that uses them; promote to a shared folder only when a second route needs them.
  • Fetch where you render. Don't hoist all data to the top and prop-drill — request memoization dedupes, so fetch in the component that needs the data.
  • Server-only by default. Keep DB clients and secret-using code in Server Components / server files; add the server-only package to a module to make an accidental client import fail at build.
  • Environment variables: only NEXT_PUBLIC_* reach the browser. Everything else is server-only — keep API keys unprefixed.
  • Metadata for SEO: export metadata or generateMetadata() per route instead of hand-writing <head> tags.
The secret-leak trap: importing a module that reads 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.

Avoid  Common pitfalls

PitfallWhy it hurtsInstead
"use client" at the top of the treeTurns the whole subtree into client JS; loses RSC benefitsMark only the interactive leaf components
useEffect + fetch for initial dataClient waterfall, no SSR data, worse LCPFetch in an async Server Component
Sequential awaitsRequest waterfall — each waits for the lastPromise.all to parallelise independent fetches
Assuming the old caching defaultStale (or uncached) data after a version bumpSet cache/revalidate explicitly
Unauthenticated Server ActionsA public endpoint anyone can callAuth + validate inside every action
<img> instead of next/imageLayout shift, oversized downloadsnext/image with dimensions

End to end  Worked example: a product page done right

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.

Step 1 · Static shell, streamed dynamic hole

// 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
    </>
  );
}

Step 2 · The interactive leaf is the only client code

"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>;
}

Step 3 · The mutation is a Server Action

"use server";
export async function addToCart(id) {
  const user = await requireSession();     // auth inside the action
  await db.cart.add(user.id, id);
  revalidateTag("cart");
}
Why this is the "right" shape: the product info is static and instant; the stock count is dynamic but streamed so it never blocks the shell; only the button ships JavaScript; and the write is an authenticated Server Action that revalidates the affected cache tag. Each concern uses the tool built for it — that's Next.js with the grain, not against it.

Cheat sheet

QuestionShort 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.

Knowledge check

Six questions. Pick an answer for each, then check your score.

1. In the App Router, a component with no directive is…

2. You need an onClick handler on a button inside a mostly-static page. Best practice?

3. Which forces a route into dynamic rendering?

4. What's the correct way to handle a form submission that writes to the database?

5. A secret API key must stay off the browser. What keeps it server-only?

6. Your app upgraded from Next 14 to 15 and data looks stale/uncached unexpectedly. Likely cause?

Next steps

🔗 API styles

REST vs GraphQL vs gRPC — how the data your Server Components fetch is exposed.

◼ GraphQL deep-dive

Schemas & resolvers — if your Next.js data layer speaks GraphQL.

🧵 Concurrency design

The backend it calls — capacity, retries & idempotency.

📓 All tutorials

The hub — LLMs, agents, data & infra.