Skip to content

Next.js

Next.js is a React framework: routing, a build pipeline, server rendering, data fetching and deployment conventions on top of React. Since the App Router (stable in Next.js 14), the default is server-first: components render on the server unless you explicitly opt into the client.

“The App Router is file-system routing over app/: folders are URL segments, and page.tsx, layout.tsx, loading.tsx, error.tsx and route.ts give each segment its behaviour. Components are server components by default — they run only on the server, can be async, can query the database directly and ship no JavaScript. 'use client' at the top of a file makes it and its imports client components, which can use state, effects and browser APIs. Layouts nest and persist across navigation, so they do not re-render. Data is fetched in server components with fetch or direct queries, and caching is explicit: fetch is cached by default with revalidation controls, while dynamic APIs like cookies() opt the route into dynamic rendering. Mutations go through Server Actions or route handlers.”

app/
layout.tsx root layout (required, renders <html> and <body>)
page.tsx /
dashboard/
layout.tsx wraps every /dashboard/* route, persists across navigation
page.tsx /dashboard
loading.tsx Suspense fallback for the segment
error.tsx error boundary for the segment
api/users/route.ts /api/users (route handler)
File Role
page.tsx The route’s UI; makes the segment publicly routable
layout.tsx Shared shell; receives children; does not remount on navigation
template.tsx Like a layout but remounts on navigation
loading.tsx Wraps the segment in Suspense
error.tsx Client error boundary ('use client' required)
not-found.tsx Rendered by notFound()
route.ts HTTP handler for GET/POST/… on that path

Dynamic segments use [id], catch-all [...slug], optional catch-all [[...slug]], and route groups (marketing) which organise files without adding a URL segment.

app/users/page.tsx
// Server component: no directive needed, async allowed.
import { db } from '@/lib/db';
export default async function UsersPage() {
const users = await db.user.findMany();
return <ul>{users.map((u) => <li key={u.id}><UserCard user={u} /></li>)}</ul>;
}
app/users/user-card.tsx
'use client';
export function UserCard({ user }: { user: User }) {
const [open, setOpen] = useState(false);
return (
<>
<button onClick={() => setOpen(!open)} aria-expanded={open}>{user.name}</button>
{open && <p>{user.email}</p>}
</>
);
}
Server component Client component
Runs Server only Server (for HTML) and browser
Can be async Yes No
Hooks / state / browser APIs No Yes
Ships JavaScript No Yes
Secrets, direct DB access Yes No

The boundary is 'use client', and it is viral downwards: everything a client component imports joins the client bundle. Push the directive as far down the tree as possible — a page can be a server component that renders one interactive island. Props crossing the boundary must be serialisable: no functions or class instances, unless the function is a Server Action reference.

app/products/page.tsx
export default async function Products() {
const res = await fetch('https://api.example.com/products', {
next: { revalidate: 60, tags: ['products'] }, // cache, revalidate at most every 60s
});
if (!res.ok) throw new Error('Failed to load products');
const products: Product[] = await res.json();
return <ProductGrid products={products} />;
}

Controls worth naming:

  • cache: 'force-cache' — cache indefinitely (the default for fetch in the App Router).
  • cache: 'no-store' — fetch on every request; makes the route dynamic.
  • next: { revalidate: n } — time-based revalidation (ISR semantics).
  • revalidatePath() / revalidateTag() — on-demand invalidation after a mutation.
  • Dynamic APIs — cookies(), headers(), searchParams opt a route into dynamic rendering.
Mode When HTML is produced How you opt in
Static (SSG) At build time Default when the route uses no dynamic APIs
Dynamic (SSR) Per request cookies(), headers(), no-store, force-dynamic
ISR At build, then revalidated revalidate on fetch or the segment
Streaming Progressively, per request Suspense boundaries around slow subtrees

Streaming changes architecture: instead of awaiting everything before sending HTML, wrap slow parts in <Suspense> and send the shell immediately. loading.tsx is sugar for exactly that at segment level.

Mutations: Server Actions and route handlers

Section titled “Mutations: Server Actions and route handlers”
app/actions.ts
'use server';
import { revalidatePath } from 'next/cache';
export async function createTodo(formData: FormData) {
const title = String(formData.get('title') ?? '').trim();
if (!title) throw new Error('Title is required');
await db.todo.create({ data: { title } });
revalidatePath('/todos');
}

Used as <form action={createTodo}> in a server component, this is the idiomatic mutation path: the mutation is co-located with the UI in the same round trip. Use route.ts when you need a real public HTTP API, custom headers, streaming responses or a non-React consumer:

app/api/users/route.ts
export async function GET() {
return Response.json(await db.user.findMany());
}

next build produces a Node server by default, or a static export with output: 'export', which disables dynamic server features, mutations and ISR. Vercel is the reference platform, but the Node output runs anywhere — Docker, Fly.io, any container platform. NEXT_PUBLIC_* variables are inlined into the client bundle at build time, so never put a secret there.

  1. Why can a client component not be async?
  2. What happens to props when they cross from a server to a client component?
  3. How does a layout avoid re-rendering, and when does a template not?
  4. Which cache would serve a stale product page, and how do you invalidate it?
  5. When would you choose a route handler over a Server Action?
  • Marking the root layout 'use client'. It makes the whole app client-rendered.
  • Passing functions across the boundary. Not serialisable; use a Server Action.
  • Assuming fetch is uncached. It is cached by default in the App Router.
  • Fetching in useEffect what a server component could fetch. You lose streaming and add a waterfall.
  • Expecting error.tsx to catch the layout above it. Error boundaries only catch below them, and never catch event-handler errors.
  • Leaking secrets through NEXT_PUBLIC_. It is public by definition.