Learnings

Tutorial 2 of 4

Next.js Essentials

Next.js is a framework built on React. You still write React components, and Next adds the parts React leaves out: routing, a server, data fetching, caching and deployment. Examples use Next 16 with the App Router and TypeScript.

Create the app

The defaults give you TypeScript, Tailwind CSS, a linter and the App Router. The structure:

Concept: a Next app runs in two places. Some code runs on the server, some in the browser. Most of this tutorial is about knowing which is which.

Pages and routes

Folders inside app/ are URL segments. A folder becomes a page when it contains page.tsx. There is no router config.

FileURL
app/page.tsx/
app/about/page.tsx/about
app/users/[id]/page.tsx/users/42, /users/7
app/(shop)/cart/page.tsx/cart (parentheses group folders without changing the URL)

Layouts and special files

A layout.tsx wraps every page in its folder and below. It stays mounted while you navigate, so the nav does not re-render.

Next looks for a few file names in each route folder and wires them up for you:

FileShown when
loading.tsxThe page is still fetching data
error.tsxThe page threw an error (must start with "use client")
not-found.tsxYou call notFound() or no route matches

Server and client components

This is the main idea of Next. Every component is a server component by default. It runs only on the server, and its code never reaches the browser. Add "use client" at the top of a file when the component needs the browser.

NeedServer componentClient component
Read the database, use secretsYesNo
async / await in the componentYesNo
useState, useEffectNoYes
onClick, onChangeNoYes
Adds JavaScript to the browser bundleNoYes

The usual pattern: the page is a server component that fetches data, and it passes that data to a small client component for the interactive part.

Rule of thumb: start on the server. Move to the client only the smallest piece that needs state or clicks.

Data fetching and caching

In a server component you just await. No useEffect, no loading state, and the user receives finished HTML.

By default each request fetches fresh data. You opt in to caching per call:

Need two things at once? Start both, then await together: const [user, posts] = await Promise.all([getUser(), getPosts()]);

Server Actions: forms and mutations

A Server Action is a function marked "use server". You pass it to a form, and Next calls it on the server when the form submits. No API endpoint and no fetch to write.

Important: a Server Action is a public endpoint under the hood. Validate the input and check the user inside every action.

Route handlers: API endpoints

A route.ts file is an HTTP endpoint. Export a function per method.

Use route handlers for things called from outside your UI: webhooks, mobile apps, other services. For your own pages, server components and Server Actions are simpler.

Auth

The pattern: a Server Action logs in and stores the token in an httpOnly cookie (JavaScript in the browser cannot read it). A proxy file blocks protected URLs before they render. Server code reads the cookie when it needs the user.

1. Log in and set the cookie

2. Block protected routes

Before Next 16 this file was called middleware.ts and the function middleware. Same idea.

3. Use the session on the server

Important: the proxy is a fast first check, not the only one. Check the session again where the data is read, as the page above does.

For Google or GitHub login, password reset and session rotation, use a library instead of writing it yourself: Auth.js, Better Auth or Clerk.

Styling, images and fonts

Tailwind is already set up by create-next-app. CSS Modules also work with no setup.

Image resizes the file, serves a modern format, lazy loads it, and reserves space so the page does not jump. Put the file in public/.

next/font downloads the font at build time and serves it from your own domain. No request to Google from the browser, no flash of the wrong font.

Metadata and SEO

Export metadata from a page or layout. Next writes the <title> and meta tags into the server HTML, so search engines and link previews see them.

Environment variables

Read them with process.env.API_URL. Only names starting with NEXT_PUBLIC_ are sent to the browser. Everything else stays on the server, so secrets are safe in server components, actions and route handlers.

From Figma to pages

The mapping is the same as in React, with a Next home for each piece:

In FigmaIn Next
Variables (colors, spacing)@theme block in app/globals.css
Component and variantsFile in components/, variants as props
Frame (a screen)app/<route>/page.tsx
Shared header, sidebarlayout.tsx
Imagespublic/ + next/image
Text styles and fontsnext/font

With an AI agent (Figma MCP)

Tell the agent which parts are interactive. Only those become client components. The rest stays on the server.

How pages get rendered

Next decides per route, based on what the page uses.

ModeHTML is builtTriggered byGood for
StaticOnce, at build timeNo request data, cached fetchesMarketing pages, docs
RevalidatedAt build, then refreshed on a timerrevalidate: 60Product lists, blogs
DynamicOn every requestcookies(), headers(), searchParams, uncached fetchesDashboards, anything per user

npm run build prints which mode each route got. For dynamic segments you can prebuild known pages with generateStaticParams.

Build and deploy

Unlike a plain React build, this is a running Node server, not a folder of static files. Three common ways to host it:

  • Vercel: connect the Git repo and push. Zero config.
  • Docker or Kubernetes: set output: "standalone" in next.config.ts, copy .next/standalone into the image, run node server.js.
  • Static only: set output: "export" to get plain files, but you lose server features (actions, cookies, dynamic rendering).

The mental model

  • Folders are routes. Special file names (page, layout, loading, error) are roles.
  • Components run on the server unless you say "use client".
  • Read data by awaiting in server components. Change data with Server Actions.
  • Secrets and cookies live on the server. The browser gets HTML and only the JavaScript it needs.
  • Caching is opt in, per fetch.

To see exactly what each of these replaced in plain React, open React vs Next.