Explain it simply
Explain it simply
A chef tasting a dish while cooking in the kitchen is different from preparing a hundred plates in advance for a banquet. At the banquet, if an ingredient is missing, there is no time to run to the shop.
next dev is the tasting kind of cooking: it compiles a page only when you open it. next build is the banquet preparation: it compiles every route at once, checks types and renders static pages ahead of time. That is why problems you never saw in dev appear during the build.
Problem → Why → Solution
The problem: a page that works in dev and breaks the build
A developer fetches the app's own Route Handler through a localhost URL inside the notes page. While next dev was running, a server sat on localhost:3000, so it worked. On release day CI runs next build, which tries to prerender this page. At that moment no server is listening on localhost:3000, the fetch fails and the whole build stops.
At the same time, the team notices that NEXT_PUBLIC_SITE_URL was changed in the hosting dashboard, yet the code in the browser still uses the old URL.
export default async function NotesPage() {
// Fine in next dev; during next build nothing listens on localhost:3000
const res = await fetch("http://localhost:3000/api/notes");
const notes: { id: string; title: string }[] = await res.json();
return (
<ul>
{notes.map((n) => <li key={n.id}>{n.title}</li>)}
</ul>
);
}Why does this happen?
A Server Component already runs on the server, so it should call the data-layer function directly instead of calling its own API over HTTP. The build may render pages before any server exists, so code that depends on localhost breaks. NEXT_PUBLIC_ variables are written into the JavaScript as literal text at build time, so changing one requires a new build.
Core concept: what the build checks that dev does not
next build writes an output optimised for production into the .next folder. Along the way it does three jobs the dev server skips. First, it compiles every route and stops if there are TypeScript type errors. Second, it decides for each route whether it is static (rendered ahead of time at build) or dynamic (rendered per request), and renders the static ones. Your Server Component code genuinely runs at this step, so the data and environment variables it needs must exist on the build machine. Third, it minifies client JavaScript and splits it into chunks.
next start then runs that output in production mode. So "pnpm build && pnpm start" is the closest you can get to production on your own machine. Shorter error messages and no hot reload are part of that realism.
| next dev | next build + next start | |
|---|---|---|
| Compiling | One page at a time, on demand | Every route, up front |
| Type errors | Shown in the editor only | Fail the build |
| Static rendering | Re-rendered on every request | Once, at build time |
| Error display | Detailed overlay | Users see only a digest |
Before a release, run these steps in a clean environment such as CI. CI exposes things that only work because of a leftover .env.local or cache on your laptop. Do not ignore build warnings just because they are not errors; understand the cause before accepting them.
Treat the release itself as a checklist rather than a feeling. Code checks (types, lint, tests, build) prove the app can be built. Environment checks prove every variable exists in the target. Operational checks prove you can watch it and undo it: monitoring is on, a backup exists and the previous version can be redeployed.
- Types and tests go first
- Build prerenders static pages
- Rehearse production with next start
- Release only with a rollback ready
Always remember that the data and env values present on the build machine get frozen into static pages.
General pattern: package.json scripts
{
"scripts": {
"dev": "next dev",
"typecheck": "tsc --noEmit",
"lint": "<your linter command>",
"test": "vitest run",
"build": "next build",
"start": "next start"
}
}Separate typecheck, lint and test scripts let CI and teammates run exactly the same commands. Recent Next.js versions no longer lint during next build, so keep lint as its own step.
Example: four commands before every release
Run these commands in order. If one fails, stop and fix it before moving to the next. typecheck is a script you define yourself in package.json (tsc --noEmit).
pnpm typecheck
pnpm test
pnpm build
pnpm start
# Check in a browser
# http://localhost:3000Code breakdown
- Fast checks first
pnpm typecheckThe type check finishes in seconds, so it runs first. Finding a type error now beats discovering it at the end of a long build.
- Behaviour checks
pnpm testUnit and component tests confirm the rules still hold. In CI this must run once and exit rather than staying in watch mode.
- The production build
pnpm buildCompiles every route and prerenders static pages, then prints the route list marked with ○ (static) and ƒ (dynamic). Check each route has the type you expected.
- Production mode, locally
pnpm startRuns the build output in production mode on port 3000. Open a browser and smoke-test the key flows: login, creating a note, images and metadata.
The production build succeeds, and key user flows work in production-like mode.Reading the build output
After a build, Next.js lists every route with a symbol. Columns and size details vary between versions, so the sample below is abridged. The symbols are what matter.
Route (app)
┌ ○ /
├ ○ /about
├ ● /notes/[slug] (generateStaticParams)
├ ƒ /dashboard
└ ƒ /api/notes
○ (Static) prerendered as static content
● (SSG) prerendered as static HTML (uses generateStaticParams)
ƒ (Dynamic) server-rendered on demand/dashboard being ƒ is correct because it reads cookies. But if /about, which is the same for everyone, shows ƒ, something is using a dynamic API unnecessarily. The opposite is more dangerous: a page that should show per-user data marked ○ is serving build-time data to everyone.
Environment variables: build time versus run time
| Variable | When it is read | To change its value |
|---|---|---|
| NEXT_PUBLIC_SITE_URL | Inlined into browser JS at next build | Rebuild |
| DATABASE_URL (in a dynamic route) | On the server, per request | Restart the server |
| Server variable read in a static page | Once at build, frozen into the HTML | Rebuild |
One build, many environments
If you want to promote one build from staging to production, NEXT_PUBLIC_ values cannot differ between them, because they are frozen into the build. Read values that must differ per environment on the server at run time and pass them to the client as props from a Server Component.
Planning migrations and rollback
1. Take a backup
Before any release that changes the database schema, take a backup, and occasionally prove you can restore it. A backup you have never restored is not a guarantee.
2. Make migrations backward compatible
Instead of renaming a column, add a new one so both the old and new code keep working, and drop the old column in a later release. Then rolling the code back does not clash with the database.
3. Know which version you would roll back to
Mark every release with a git tag or commit SHA and write down how to redeploy the previous one. At 2 a.m. during an incident there is no time to work it out.
In real projects
In real projects
Most teams keep their release checklist as a file in the repository (for example RELEASE.md) or as a pull request template. CI automates most items, leaving only the human judgement calls, such as "is the migration backward compatible?" and "what is the rollback version?", as checkboxes.
On every pull request the CI pipeline installs exactly what the lockfile says with pnpm install --frozen-lockfile, then runs typecheck, lint, tests and the build. After merging to main, the build goes to staging first, and only reaches production once the smoke test passes. Release notes record the commit SHA, the changes and whether a migration is included, so in an incident everyone knows immediately which version to roll back to.
Common mistakes
Common mistakes
- Testing only in development mode and running next build for the first time on deploy day. Type errors, fetches to a server that does not exist at build time and pages that turned static all surface on release day.
- Changing a NEXT_PUBLIC_ variable in the hosting dashboard without rebuilding. The browser JavaScript still holds the old value as literal text. Worse, naming a secret with NEXT_PUBLIC_ puts it in files anyone can download.
- Running a database migration alongside the code with no rollback plan. If the code is rolled back but the column is already gone, the old version is broken too.
- Ignoring build warnings because they are "not errors". Warnings often flag early that a route meant to be dynamic went static, or that a dependency has a problem.
Mini challenge
Try it yourself: a pre-build environment check
Write a preflight function that CI runs before next build. Check an environment object with zod and list anything missing, invalid, or secret-looking yet prefixed with NEXT_PUBLIC_ (a variable that would leak into the browser). Allow the build only when there are no problems.
- DATABASE_URL must start with postgres://, and AUTH_SECRET must be at least 32 characters
- NEXT_PUBLIC_SITE_URL must be a valid URL
- Report a missing variable as "missing"
- Warn about names that start with NEXT_PUBLIC_ and contain SECRET, PASSWORD, TOKEN, DATABASE_URL or PRIVATE
import { z } from "zod";
type Env = Record<string, string | undefined>;
// TODO: an EnvSchema with DATABASE_URL, AUTH_SECRET and NEXT_PUBLIC_SITE_URL
export function preflight(env: Env): string[] {
const problems: string[] = [];
// TODO: safeParse the env and turn each issue into "NAME: missing" or "NAME: reason"
// TODO: flag NEXT_PUBLIC_ variables whose names look secret
return problems;
}
// TODO: report(name, env) prints "ready to build" or "BLOCKED" plus each problem
// TODO: try it with a broken "staging" env and a correct "production" envExpected: "staging: BLOCKED" with three lines below it (AUTH_SECRET too short, NEXT_PUBLIC_SITE_URL missing, NEXT_PUBLIC_API_TOKEN looks secret), then "production: ready to build".
Show hint
Each entry in safeParse's error.issues has path[0], the variable name. If env[name] is undefined write "missing", otherwise use issue.message. You can give your own message with z.string().min(32, "message").
Show solution
import { z } from "zod";
// Run in CI before `next build`
const EnvSchema = z.object({
DATABASE_URL: z.string().startsWith("postgres://"),
AUTH_SECRET: z.string().min(32, "must be at least 32 characters"),
NEXT_PUBLIC_SITE_URL: z.string().url(),
});
const SECRET_WORDS = ["SECRET", "PASSWORD", "TOKEN", "DATABASE_URL", "PRIVATE"];
type Env = Record<string, string | undefined>;
export function preflight(env: Env): string[] {
const problems: string[] = [];
const parsed = EnvSchema.safeParse(env);
if (!parsed.success) {
for (const issue of parsed.error.issues) {
const name = String(issue.path[0]);
problems.push(`${name}: ${env[name] === undefined ? "missing" : issue.message}`);
}
}
for (const key of Object.keys(env)) {
const looksSecret = SECRET_WORDS.some((word) => key.includes(word));
if (key.startsWith("NEXT_PUBLIC_") && looksSecret) {
problems.push(`${key}: looks secret but NEXT_PUBLIC_ inlines it into browser JS`);
}
}
return problems;
}
function report(name: string, env: Env) {
const problems = preflight(env);
console.log(`${name}: ${problems.length === 0 ? "ready to build" : "BLOCKED"}`);
problems.forEach((p) => console.log(` - ${p}`));
}
report("staging", {
DATABASE_URL: "postgres://app@db.internal:5432/notes",
AUTH_SECRET: "short",
NEXT_PUBLIC_API_TOKEN: "sk_live_123",
});
report("production", {
DATABASE_URL: "postgres://app@db.internal:5432/notes",
AUTH_SECRET: "x".repeat(40),
NEXT_PUBLIC_SITE_URL: "https://notes.example.com",
});Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- next build compiles and type-checks every route and renders static pages at build time
- Rehearse production mode locally with pnpm build && pnpm start before each release
- NEXT_PUBLIC_ variables are frozen into the build, so changing one means rebuilding
- Plan a backup, a backward-compatible migration and a rollback version for every release
Next.js — Production Checklist — Next.js
Next.js — Production Checklist — Next.js