Env vars, config and deployment
Env variables hold config and secrets, but only some of them may reach the browser. This note covers server vs NEXT_PUBLIC_ variables, validating env with Zod, next.config (standalone output, redirects) and deploying with Docker or Vercel.
70.1 Problem: undefined in the browser
- API_URL is in .env.local; a Client Component reads process.env.API_URL on click.
- After a build the console shows undefined, although the same variable works on the server.
"use client"; export default function LoadButton() { function handleClick() { const url = process.env.API_URL; console.log("API URL:", url); } return ( <button onClick={handleClick}> Load products </button> );}[button] Load productsConsole: API URL: undefined70.2 Why undefined?
- .env values are loaded into the Node.js process on the server; Server Components, Server Actions and Route Handlers can read them.
- Client Component code runs in the browser, where your env file does not exist.
- At build time Next.js copies only NEXT_PUBLIC_ variables into the JS bundle; everything else is undefined in the browser. A security feature, not a bug.
- Step 1
1..env.local is loaded into the server process
- Step 2
2.Server code (components, actions, route handlers) reads every variable
- Step 3
3.npm run build inlines only NEXT_PUBLIC_* into the client bundle
- Step 4
4.Browser: NEXT_PUBLIC_API_URL = string, API_URL = undefined
70.3 Env file: server vs public
- .env.local sits in the project root; each line is NAME=value.
- DATABASE_URL and PAYMENT_SECRET are server-only, so no prefix.
- NEXT_PUBLIC_API_URL is needed in the browser and is public anyway.
- Never commit it: the create-next-app .gitignore already ignores it.
# .env.local (project root, ignored by git)# server only: secretDATABASE_URL=postgres://shop:pass@db:5432/shopPAYMENT_SECRET=sk_live_8f3k2m9q# browser needs this tooNEXT_PUBLIC_API_URL=https://api.shop.in70.4 Fix: the NEXT_PUBLIC_ prefix
- Only the name changes: process.env.NEXT_PUBLIC_API_URL.
- At build time Next.js replaces the whole expression with the actual string; the bundle literally contains https://api.shop.in.
"use client"; export default function LoadButton() { function handleClick() { const url = process.env.NEXT_PUBLIC_API_URL; console.log("API URL:", url); } return ( <button onClick={handleClick}> Load products </button> );}[button] Load productsConsole: API URL: https://api.shop.in| Point | Normal env var | NEXT_PUBLIC_ env var |
|---|---|---|
| Available in | Server only | Server and browser |
| How it reaches the browser | Never | Inlined into the bundle at build time |
| Change takes effect | On server restart | Only after a rebuild |
| Use for | Secrets: DB URL, API keys | Public values: public API URL |
70.5 Env validation with Zod
- If DATABASE_URL is missing in production, the app starts but crashes on the first query.
- lib/env.ts imports server-only, so it can never be imported into a Client Component.
- A Zod schema lists every variable's type and parses process.env.
- With DATABASE_URL missing, the build itself fails and names the variable.
// lib/env.tsimport "server-only";import { z } from "zod"; const schema = z.object({ DATABASE_URL: z.url(), PAYMENT_SECRET: z.string().min(10), NEXT_PUBLIC_API_URL: z.url(),}); export const env = schema.parse(process.env);$ npm run buildError [ZodError]: [ path: [ "DATABASE_URL" ] Invalid input: expected string, received undefined> Build error occurred70.6 Checkpoint: which URL shows up?
- Built, then changed NEXT_PUBLIC_API_URL to api2 and restarted without a rebuild.
- Answer: the old URL. NEXT_PUBLIC_ values are fixed into the bundle at build time.
- A public value change needs a rebuild; every environment gets its own build with its own public values.
$ npm run build# after the build, edit .env.local:# NEXT_PUBLIC_API_URL=https://api2.shop.in$ npm start[button] Load productsConsole: API URL: https://api.shop.in70.7 next.config: standalone + redirects
- output: "standalone": after the build a small server file and only the required node_modules go into .next/standalone.
- redirects(): sends the old /offers URL to /sale with a permanent redirect.
- Start the standalone server with node; /offers returns 308.
// next.config.tsimport type { NextConfig } from "next"; const nextConfig: NextConfig = { output: "standalone", async redirects() { return [{ source: "/offers", destination: "/sale", permanent: true, }]; },}; export default nextConfig;$ npm run build✓ Compiled successfully $ PORT=8080 node .next/standalone/server.js▲ Next.js 16.4.5- Local: http://localhost:8080✓ Ready in 0ms $ curl -I localhost:8080/offersHTTP/1.1 308 Permanent Redirectlocation: /sale70.8 Docker: multi-stage build
- Stage 1 copies the code and builds with npm ci && npm run build.
- Stage 2 copies only the standalone folder, the static files and public, then runs node server.js.
- The final image stays small; secrets are never written in the Dockerfile but passed as env vars when the container runs.
# DockerfileFROM node:22-alpine AS buildWORKDIR /appCOPY . .RUN npm ci && npm run build FROM node:22-alpineWORKDIR /appENV NODE_ENV=productionCOPY --from=build /app/.next/standalone ./COPY --from=build /app/.next/static ./.next/staticCOPY --from=build /app/public ./publicEXPOSE 3000CMD ["node", "server.js"]- Step 1
1.Stage build: node:22-alpine, COPY . .
- Step 2
2.npm ci && npm run build -> .next/standalone
- Step 3
3.Stage run: copy standalone + .next/static + public only
- Step 4
4.docker run -e DATABASE_URL=... (secrets at runtime)
- Step 5
5.CMD node server.js on port 3000
70.9 Deploying on Vercel
- Step 1
1.Connect the GitHub repo
- Step 2
2.git push -> Vercel builds automatically
- Step 3
3.Every pull request gets a preview URL
- Step 4
4.Merge into main -> production deploy
Env vars are set in the Vercel dashboard separately for production and preview
| Option | How it runs | Good for |
|---|---|---|
| Vercel | Git push, automatic builds, preview URLs | Easiest, made by the Next.js team |
| next start | Any Node.js server | Your own VM / PaaS |
| Docker + standalone | Small image, runs anywhere | AWS, Azure, own VPS |
| Static export | Plain HTML files | Apps with no server features |
70.10 Common mistakes
- The secret was undefined in a Client Component, so someone renamed it NEXT_PUBLIC_PAYMENT_SECRET: it works, but now the key is in the bundle and visible in DevTools.
- Fix: do secret work in a Server Action or Route Handler, where the secret is read on the server.
- Expecting a NEXT_PUBLIC_ change to apply after a restart without a rebuild.
- Myth: Next.js only deploys on Vercel. next start runs on any Node server, Docker standalone runs anywhere, static export gives plain HTML.
// Wrong: PayButton.tsx, the secret ends up in the bundle"use client"; export function PayButton() { async function pay() { const key = process.env.NEXT_PUBLIC_PAYMENT_SECRET; await fetch("https://pay.in/charge", { headers: { Authorization: key! }, }); } return <button onClick={pay}>Pay</button>;}// Right: actions.ts, the secret stays on the server"use server"; export async function pay() { const key = process.env.PAYMENT_SECRET; await fetch("https://pay.in/charge", { method: "POST", headers: { Authorization: `Bearer ${key}` }, });}70.11 Best practices
- Never put secrets in NEXT_PUBLIC_ and never commit .env.local.
- Commit a .env.example with only the variable names so the team knows what to set.
- Validate env as soon as the app starts (or builds).
- Keep production secrets in the hosting dashboard or a secret manager, not in code.
70.12 Interview tips
- Normal env vars are available only on the server and never reach the browser.
- NEXT_PUBLIC_ vars are inlined into the client bundle at build time: public, and a change needs a rebuild.
- Secrets always stay server side (Server Actions, Route Handlers).
- Deploy with Vercel, or with output: "standalone" in a multi-stage Docker image.