SkillPilotAI

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.
React (TSX)
"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>  );}
Output
[button] Load productsConsole: API URL: undefined

70.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.
Where env values go
  1. 1..env.local is loaded into the server process

  2. 2.Server code (components, actions, route handlers) reads every variable

  3. 3.npm run build inlines only NEXT_PUBLIC_* into the client bundle

  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.
Terminal
# .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.in

70.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.
React (TSX)
"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>  );}
Output
[button] Load productsConsole: API URL: https://api.shop.in
PointNormal env varNEXT_PUBLIC_ env var
Available inServer onlyServer and browser
How it reaches the browserNeverInlined into the bundle at build time
Change takes effectOn server restartOnly after a rebuild
Use forSecrets: DB URL, API keysPublic 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.
TypeScript
// 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);
Output
$ npm run buildError [ZodError]: [  path: [ "DATABASE_URL" ]  Invalid input: expected string,  received undefined> Build error occurred

70.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.
Terminal
$ npm run build# after the build, edit .env.local:# NEXT_PUBLIC_API_URL=https://api2.shop.in$ npm start
Output
[button] Load productsConsole: API URL: https://api.shop.in

70.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.
TypeScript
// next.config.tsimport type { NextConfig } from "next"; const nextConfig: NextConfig = {  output: "standalone",  async redirects() {    return [{      source: "/offers",      destination: "/sale",      permanent: true,    }];  },}; export default nextConfig;
Output
$ 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: /sale

70.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.
Terminal
# 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"]
Docker multi-stage pipeline
  1. 1.Stage build: node:22-alpine, COPY . .

  2. 2.npm ci && npm run build -> .next/standalone

  3. 3.Stage run: copy standalone + .next/static + public only

  4. 4.docker run -e DATABASE_URL=... (secrets at runtime)

  5. 5.CMD node server.js on port 3000

70.9 Deploying on Vercel

Vercel Git workflow
  1. 1.Connect the GitHub repo

  2. 2.git push -> Vercel builds automatically

  3. 3.Every pull request gets a preview URL

  4. 4.Merge into main -> production deploy

Env vars are set in the Vercel dashboard separately for production and preview

OptionHow it runsGood for
VercelGit push, automatic builds, preview URLsEasiest, made by the Next.js team
next startAny Node.js serverYour own VM / PaaS
Docker + standaloneSmall image, runs anywhereAWS, Azure, own VPS
Static exportPlain HTML filesApps 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.
React (TSX)
// 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>;}
TypeScript
// 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.