Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Next.js Environment Variables: NEXT_PUBLIC_, Build-Time Inlining, and Runtime Config

The prefix decides whether a value is compiled into the browser bundle or stays on the server. One image, two environments, and the choice that follows from it.

~4 min readNext.js
#Next.js#Configuration#Deployment#Security
3D illustration of key-value chips split into a browser lane and a sealed server cube

Quick Summary

An environment variable in Next.js has two possible destinies: it is inlined into the JavaScript bundle at build time, or it stays on the server and is read at request time. The NEXT_PUBLIC_ prefix decides that. There is no third option, and there is no such thing as a "secret that is only used a little" on the client.

The most expensive mistake is treating NEXT_PUBLIC_ as configuration. It is compiled in, so one Docker image cannot serve staging and production with different API URLs; you need two builds, or a runtime lookup that is not an env var.

Everything else follows from three facts: .env.local is loaded automatically and must never be committed, process.env.X on the server is evaluated when the module runs (which for a statically rendered page is at build time), and next dev reloads env changes while a running next start never does.

Basic Syntax & Core Signatures

bash
# .env — committed defaults, no secrets NEXT_PUBLIC_SITE_URL=https://example.com NEXT_PUBLIC_ANALYTICS_ID= # .env.local — never committed DATABASE_URL=postgres://user:pass@localhost:5432/app STRIPE_SECRET_KEY=sk_test_... SESSION_SECRET=...
ts
// lib/env.ts — fail fast at startup, not at the third request import { z } from "zod"; const schema = z.object({ DATABASE_URL: z.string().url(), SESSION_SECRET: z.string().min(32), STRIPE_SECRET_KEY: z.string().startsWith("sk_"), NEXT_PUBLIC_SITE_URL: z.string().url(), }); export const env = schema.parse(process.env); // Throws at import time: a deploy with a missing variable never starts serving
ts
// instrumentation.ts — runs once per server start export async function register() { if (process.env.NEXT_RUNTIME === "nodejs") { await import("./lib/env"); // validate before the first request } }
ts
// next.config.ts — values here are also compiled into the build import type { NextConfig } from "next"; const nextConfig: NextConfig = { env: { BUILD_TIME: new Date().toISOString(), // available in both runtimes, inlined }, output: "standalone", }; export default nextConfig;

Load order, later wins: process.env (real environment) → .env.$(NODE_ENV).local → .env.local → .env.$(NODE_ENV) → .env. So a variable exported by the platform overrides every file, and .env.development.local beats .env. Only .env.local is skipped in test.

Key Comparison Table

Variable formAvailable in browserInlined at buildCan be changed after buildSafe for secrets
DATABASE_URLNoServer bundle onlyYes, on the serverYes
NEXT_PUBLIC_API_URLYesYesNo, requires rebuildNo
next.config.ts env keyYesYesNoNo
publicRuntimeConfig (Pages Router)YesNoYesNo
unstable_runtimeEnv / dynamic lookupDepends on call siteNoYesServer only
Non-prefixed var read in a client componentNo (becomes undefined)Non/an/a
FileCommittedLoaded in devLoaded in prodPurpose
.envYesYesYesShared defaults
.env.localNoYesYesLocal secrets
.env.developmentYesYesNoDev defaults
.env.productionYesNoYesBuild-time prod values
.env.development.localNoYesNoPersonal overrides

Practical Edge Cases & Deep Dives

1. One Docker image, many environments

NEXT_PUBLIC_* is frozen at build. If the image is built once and deployed to staging and production, both will point at whichever URL was present during docker build. Two workable answers:

ts
// Read the public config at runtime instead of baking it in // app/layout.tsx (server component) → pass to the client as a prop const apiBase = process.env.PUBLIC_API_BASE_URL ?? "http://localhost:3000"; export default function RootLayout({ children }: { children: React.ReactNode }) { return <html><body><ConfigProvider apiBase={apiBase}>{children}</ConfigProvider></body></html>; }

Or build per environment in CI with build args. The prop approach keeps one image but adds a server render on every route that needs the value; the build-args approach keeps static output but doubles build time and image count.

dockerfile
# Per-environment image: the public value is baked at build ARG NEXT_PUBLIC_API_BASE_URL ENV NEXT_PUBLIC_API_BASE_URL=${NEXT_PUBLIC_API_BASE_URL} RUN npm run build

Pick one and state it in the README. Teams that half-do both end up with an image built for staging and deployed to production, and the failure is silent because the URL still resolves — it just resolves to the wrong environment.

2. A secret that leaks through a shared module

Importing a module that touches process.env.SECRET into a client component does not leak the value — the reference becomes undefined — but libraries that throw on missing config at import time break the client bundle. Worse, anything you pass down as a prop is serialised into the RSC payload and readable in the HTML. The rule: secrets stay inside functions that are only called on the server, marked with import "server-only".

ts
// lib/stripe.ts import "server-only"; // build fails if a client component imports this import Stripe from "stripe"; export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

3. Edge runtime has no dynamic process.env

On the Edge runtime, environment variables are injected per request from a build-time map. Dynamic access such as process.env[key] or destructuring the whole object returns nothing, because the bundler cannot know which keys to include. Read them by literal name:

ts
export const runtime = "edge"; export async function GET() { const key = process.env.API_KEY; // works: literal name // const key = process.env[process.env.NAME!]; -> undefined at runtime return Response.json({ ok: Boolean(key) }); }

4. Validation that does not block the build

zod validation at module scope runs during next build for statically rendered pages, which fails CI when the deploy environment has no secrets — a common and confusing error. Two options: validate only inside request handlers, or skip during build:

ts
const isBuild = process.env.NEXT_PHASE === "phase-production-build"; if (!isBuild) env; // throws locally, stays quiet during build

The alternative — validating in instrumentation.ts only — keeps build and runtime separated cleanly, at the cost of discovering a bad variable on first request rather than at build.

5. Multi-tenant configuration that cannot be an env var

A per-customer API key cannot live in process.env because it is not process-wide. Store it in the database, read it through the tenant context on the server, and never send it to the client. Env vars are for deployment-level configuration only; the moment a value differs per request or per tenant, it needs a different home.

6. .env files and the standalone output

output: "standalone" copies the server into .next/standalone but does not copy .env files unless you include them. The result is a container that starts with every variable undefined. Either use real container environment variables (recommended, they override files anyway) or copy the files explicitly in the Dockerfile:

dockerfile
COPY --from=builder /app/.next/standalone ./ COPY --from=builder /app/.next/static ./.next/static COPY --from=builder /app/public ./public # no .env copied: container env is the source of truth

Common Runtime & Configuration Mistakes

SymptomCauseFix
undefined in the browser for a server varMissing NEXT_PUBLIC_ prefixRename, or move the read to the server and pass a prop
Secret visible in view-sourcePrefixed with NEXT_PUBLIC_Remove the prefix, rebuild, rotate the leaked key
Value did not change after deployInlined at build; same image reusedRebuild, or read at runtime on the server
next build fails on CI, passes locallyValidation runs at build without secretsValidate in instrumentation.ts or guard on NEXT_PHASE
Works in next dev, not in next startDev reloads env files; prod reads them once at bootRestart the server after editing, or use platform variables
Edge route gets undefined from process.env[key]Dynamic key access is not bundledUse literal property names
.env committed by accidentNo .gitignore entryAdd .env*.local, rotate anything already pushed

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.