You put API_URL in .env.local, read process.env.API_URL in a component, and the browser logs undefined. Or you fix a value in the Vercel dashboard and production still shows the old one. Both bugs come from the same fact: Next.js resolves many process.env reads when it builds your app, not when it runs it.
TL;DR
- Client code only sees
NEXT_PUBLIC_variables (plusnext.configenv keys), and only when written asprocess.env.NEXT_PUBLIC_NAME. Computed keys and destructuring stayundefined. - Public values are pasted into server and client bundles at build time. Changing them on Vercel or in CI does nothing until you rebuild and redeploy.
- A statically prerendered page (or, in Next 14, a GET route handler) reads server env once, during
next build. Make the route dynamic to read unprefixed variables per request. - For Docker "build once, deploy many", serve per-environment public config from the server at runtime instead of using
NEXT_PUBLIC_. - Keep secrets unprefixed, guard server modules with
server-only, and validate env with a zod schema so a bad deploy fails loudly.
Build time versus request time
During next build, the bundler does a literal find-and-replace on expressions like process.env.NEXT_PUBLIC_API_URL, swapping in the value from the build machine. It does this in server and client bundles alike, and keys under env in next.config.js get the same treatment. Everything else stays a normal property lookup, and in the browser process.env is a nearly empty polyfill, so those lookups come back undefined.
| Where the code runs | What process.env.X gives you | Read when |
|---|---|---|
| Browser (Client Component) | Inlined value for NEXT_PUBLIC_ and next.config env keys, otherwise undefined | next build |
| Server Component on a static page | The build machine's environment | next build |
| Dynamic page, dynamic route handler, server action | Unprefixed variables: the running server's environment | Each request |
| Same dynamic server code | NEXT_PUBLIC_ and next.config env keys: the inlined build-time value | next build |
I checked these with a small Next.js 14 app (client chunks, static and dynamic pages, route handlers), built with one set of values and started with another. Note the last row: a force-dynamic page still rendered the build-time NEXT_PUBLIC_ value (check your version).
Undefined in the browser
Only public variables reach client code
The most common version:
"use client";
export function ApiBadge() {
// No NEXT_PUBLIC_ prefix: never inlined, so undefined in the browser.
const apiUrl = process.env.API_URL;
return <span>API: {apiUrl ?? "not configured"}</span>;
}Next.js only copies NEXT_PUBLIC_ variables into client bundles. That allowlist is deliberate: a database password can't leak because someone referenced it in the wrong file. Rename the variable and restart the dev server:
# .env.local
NEXT_PUBLIC_API_URL=https://api.example.com"use client";
export function ApiBadge() {
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
return <span>API: {apiUrl ?? "not configured"}</span>;
}The prefix makes the value public, since it ships in JavaScript every visitor downloads. Reserve it for things like a public API URL or an analytics ID.
Dynamic lookups are not inlined
This one catches people who already know about the prefix:
"use client";
function readEnv(name: string) {
return process.env[name];
}
export function FooterLinks() {
const { NEXT_PUBLIC_DOCS_URL } = process.env;
const siteUrl = readEnv("NEXT_PUBLIC_SITE_URL");
return (
<nav>
<a href={siteUrl}>Home</a>
<a href={NEXT_PUBLIC_DOCS_URL}>Docs</a>
</nav>
);
}Both links are broken in the browser. The replacement matches the exact expression process.env.NEXT_PUBLIC_SITE_URL; a computed key or destructuring pattern is not that expression, so both stay lookups on the empty browser object.
Worse, Client Components also render on the server, where process.env is real, so the server HTML can contain the value while the browser gets undefined. That can surface as a hydration mismatch warning or error, not an obvious env bug.
The fix is boring: reference every variable by its full name, once, in one module.
// lib/public-env.ts
export const publicEnv = {
siteUrl: process.env.NEXT_PUBLIC_SITE_URL,
docsUrl: process.env.NEXT_PUBLIC_DOCS_URL,
} as const;"use client";
import { publicEnv } from "@/lib/public-env";
export function FooterLinks() {
return (
<nav>
<a href={publicEnv.siteUrl}>Home</a>
<a href={publicEnv.docsUrl}>Docs</a>
</nav>
);
}Note: In my webpack build,
process.env["NEXT_PUBLIC_API_URL"]was inlined too. Don't rely on that across bundlers and versions; dot access with the full name is the documented form.
Changed the value but nothing happened
Vercel and CI need a new build
Public values are part of the build output. Editing a variable in the Vercel dashboard or CI secrets doesn't touch existing deployments, so redeploy. Restarting a server on an old .next folder doesn't help either.
Vercel also scopes variables per environment (Production, Preview, Development), so a value added only to Production is missing from preview builds. vercel env pull .env.local downloads the Development values for local work.
Check what actually got baked in
Public values are plain strings in .next/static, so grep for them before changing anything:
npx next build
grep -rl "https://api.example.com" .next/static
grep -rl "https://old-api.example.com" .next/staticIf the old URL shows up, the build saw the old value. If neither does, the variable was missing at build time or no client code references it as process.env.NEXT_PUBLIC_NAME. It doubles as a leak check: grepping for a secret's prefix, such as sk_live_, should print nothing.
Server Components frozen at build time
The App Router prerenders routes at build time whenever it can. A Server Component that only reads process.env gives it no reason to wait for a request, so the page renders once, with the build machine's values.
// app/status/page.tsx
export default function StatusPage() {
return <p>Region: {process.env.DEPLOY_REGION ?? "unknown"}</p>;
}In my test app this page was marked static (○) and kept serving the build-time value after a restart. A GET route handler returning process.env behaved the same, because Next 14 prerenders handlers that don't read the request. Next 15 made GET handlers dynamic by default, but pages that never touch request data are still prerendered, so check the route table at the end of next build.
To read env per request, make the route dynamic. This segment config works in Next 13, 14 and 15:
// app/status/page.tsx
export const dynamic = "force-dynamic";
export default function StatusPage() {
return <p>Region: {process.env.DEPLOY_REGION ?? "unknown"}</p>;
}The route then showed as ƒ (dynamic) and returned the runtime value. Next 14 also offers unstable_noStore() from next/cache; in Next 15 and later, the documented approach is to await connection() from next/server:
// app/status/page.tsx (Next 15 and later)
import { connection } from "next/server";
export default async function StatusPage() {
await connection();
return <p>Region: {process.env.DEPLOY_REGION ?? "unknown"}</p>;
}If a value changes rarely, export const revalidate = 3600 is a middle ground: the page stays static but regenerates in the background with the current environment on a self-hosted server (on Vercel, env changes still need a new deployment).
Docker: build once, deploy many
The usual container setup builds one image and promotes it from staging to production with different environment variables. That works for server-side values, but NEXT_PUBLIC_ values were fixed when next build ran inside the image.
Option 1: build one image per environment
Pass public values as build arguments so next build sees them:
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
ARG NEXT_PUBLIC_API_URL
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
RUN npm run build
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
# Docker sets HOSTNAME to the container ID; listen on all interfaces instead.
ENV HOSTNAME=0.0.0.0
ENV PORT=3000
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public
EXPOSE 3000
CMD ["node", "server.js"]docker build --build-arg NEXT_PUBLIC_API_URL=https://api.staging.example.com -t web:staging .
docker run -p 3000:3000 -e DATABASE_URL=postgres://app:secret@db:5432/app web:stagingThis assumes output: "standalone" and a public folder; adjust it to your project. Server-only values like DATABASE_URL go in at docker run time; never pass secrets as build args, which can be read back from the image history. Add a .dockerignore too, or COPY . . brings a developer's .env.local into the image and next build loads it:
node_modules
.next
.env*.localOption 2: serve public config at runtime
For one image across environments, stop using NEXT_PUBLIC_ for values that differ. Read them on the server per request and pass them down through a layout and a small context:
// app/(app)/public-config.tsx
"use client";
import { createContext, useContext, type ReactNode } from "react";
export type PublicConfig = {
apiUrl: string;
sentryDsn: string;
};
const PublicConfigContext = createContext<PublicConfig | null>(null);
export function PublicConfigProvider({
value,
children,
}: {
value: PublicConfig;
children: ReactNode;
}) {
return (
<PublicConfigContext.Provider value={value}>
{children}
</PublicConfigContext.Provider>
);
}
export function usePublicConfig(): PublicConfig {
const config = useContext(PublicConfigContext);
if (!config) {
throw new Error("usePublicConfig must be used inside <PublicConfigProvider>");
}
return config;
}// app/(app)/layout.tsx
import type { ReactNode } from "react";
import { PublicConfigProvider, type PublicConfig } from "./public-config";
// Read env per request instead of once at build time.
export const dynamic = "force-dynamic";
export default function Layout({ children }: { children: ReactNode }) {
const publicConfig: PublicConfig = {
apiUrl: process.env.API_URL ?? "",
sentryDsn: process.env.SENTRY_DSN ?? "",
};
return (
<PublicConfigProvider value={publicConfig}>{children}</PublicConfigProvider>
);
}// app/(app)/api-status.tsx
"use client";
import { useEffect, useState } from "react";
import { usePublicConfig } from "./public-config";
export function ApiStatus() {
const { apiUrl } = usePublicConfig();
const [status, setStatus] = useState("checking");
useEffect(() => {
fetch(`${apiUrl}/health`)
.then((res) => setStatus(res.ok ? "up" : `down (${res.status})`))
.catch(() => setStatus("unreachable"));
}, [apiUrl]);
return (
<p>
{apiUrl}: {status}
</p>
);
}In my test, the page got the runtime API_URL. This is also why the layout reads an unprefixed API_URL: process.env.NEXT_PUBLIC_API_URL would be inlined as the build-time string even in a force-dynamic Server Component. Because the layout is force-dynamic, every page under it renders per request, so it lives in a route group, leaving pages outside it static.
Warning: Everything a Server Component passes to a Client Component is serialized into the page. Treat
publicConfigexactly likeNEXT_PUBLIC_: no secrets, ever.
If non-React code needs the config, a dynamic route handler works, at the cost of an extra request:
// app/api/public-config/route.ts
export const dynamic = "force-dynamic";
export function GET() {
return Response.json({
apiUrl: process.env.API_URL ?? "",
sentryDsn: process.env.SENTRY_DSN ?? "",
});
}Leave out the dynamic line in Next 14 and this handler is prerendered with build-time values, the exact bug you were escaping.
How .env files are loaded
Next.js first picks a mode: next dev is development, next build and next start are production, and NODE_ENV=test gives test. Then it reads sources in this order, highest priority first:
- Real environment variables from your shell, container or host. These always beat files.
.env.development.local,.env.production.localor.env.test.local, matching the mode..env.local, except in test mode..env.development,.env.productionor.env.test..env.
The first source that defines a key wins. .env.local is skipped in tests so every machine sees the same values. Commit .env and the mode files only with safe defaults; keep *.local files out of git.
You can confirm the order with @next/env, the loader Next.js uses (the docs also suggest it for tests). Run this in an empty folder; the first command installs the package:
// check-env.mjs
import nextEnv from "@next/env";
const { loadEnvConfig } = nextEnv;
const mode = process.argv[2];
const dev = mode === "development";
if (mode === "test") process.env.NODE_ENV = "test";
const { loadedEnvFiles } = loadEnvConfig(process.cwd(), dev, { info() {}, error: console.error });
console.log(`mode: ${mode}`);
console.log(` files: ${loadedEnvFiles.map((f) => f.path).join(", ")}`);
console.log(` WHO=${process.env.WHO} ONLY_BASE=${process.env.ONLY_BASE}`);npm init -y && npm install @next/env
printf 'WHO=.env\nONLY_BASE=from .env\n' > .env
printf 'WHO=.env.local\n' > .env.local
printf 'WHO=.env.development\n' > .env.development
printf 'WHO=.env.production\n' > .env.production
printf 'WHO=.env.test\n' > .env.test
for mode in development production test; do node check-env.mjs "$mode"; done
WHO=shell node check-env.mjs productionThe node runs print:
mode: development
files: .env.local, .env.development, .env
WHO=.env.local ONLY_BASE=from .env
mode: production
files: .env.local, .env.production, .env
WHO=.env.local ONLY_BASE=from .env
mode: test
files: .env.test, .env
WHO=.env.test ONLY_BASE=from .env
mode: production
files: .env.local, .env.production, .env
WHO=shell ONLY_BASE=from .envRecent next dev versions reload .env files on change; if a value still looks stale, restart anyway. In a monorepo, Next.js reads these files from the app's directory (the one with next.config.js), not the repo root.
next.config env and middleware
The env key is build-time too
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
env: {
BUILD_SHA: process.env.VERCEL_GIT_COMMIT_SHA ?? "local",
},
};
module.exports = nextConfig;Keys under env are inlined into server and client bundles at build time, prefix or not; in my test, an unprefixed key showed up as a string literal in the client chunk. Fine for a commit SHA, dangerous for a secret.
Middleware and the Edge runtime
Middleware and Edge route handlers can read process.env, with NEXT_PUBLIC_ references inlined. Other variables depend on version and host (in Next 14, next start gives the edge sandbox the server's environment), so use static process.env.NAME references in edge code and test the deployed middleware, not only next dev.
Monorepos: Turborepo strict env mode
Turborepo 2.x runs tasks in strict environment mode by default: a task sees only variables declared in turbo.json, plus some it infers and a few system ones. So next build run through turbo never sees undeclared variables.
{
"$schema": "https://turbo.build/schema.json",
"tasks": {
"build": {
"dependsOn": ["^build"],
"env": ["NEXT_PUBLIC_*", "API_URL"],
"passThroughEnv": ["DATABASE_URL"],
"inputs": ["$TURBO_DEFAULT$", ".env*"],
"outputs": [".next/**", "!.next/cache/**"]
}
}
}In my Turborepo 2.x test, an undeclared variable arrived as undefined, and --env-mode=loose let it through, a handy way to confirm strict mode is the culprit. Variables in env also feed the cache key, so a missing entry can replay a cached build with old public values. passThroughEnv exposes a variable without changing the key, which suits DATABASE_URL. Next.js reads .env files itself, and a gitignored .env.local is not a default input: editing it replayed the stale build until I added the inputs line. Older 1.x configs use pipeline instead of tasks, so check the docs for your version.
Keep secrets on the server
The prefix, and the next.config env key, are all that stand between a secret and every visitor's browser. Never put NEXT_PUBLIC_ on an API key, token or connection string. If the client needs what a secret unlocks, call a route handler or server action that uses it.
Guard modules that read secrets with the server-only package (npm install server-only):
// lib/secrets.ts
import "server-only";
export function getStripeKey(): string {
const key = process.env.STRIPE_SECRET_KEY;
if (!key) {
throw new Error("STRIPE_SECRET_KEY is not set");
}
return key;
}If a Client Component imports this module, directly or indirectly, the build fails; on Next 14 the error pointed at the import "server-only" line with an import trace back to the component.
One catch: outside Next.js the package throws on import (it only resolves to an empty module under the React Server Components condition), so plain Node scripts like seeds or migrations can't import guarded modules.
Validate env at startup with zod
A missing variable usually fails far from its cause: a fetch to undefined/health, or a database client rejecting an invalid URL three layers down. A small schema turns that into one clear message.
// lib/env.ts
import { z } from "zod";
const serverSchema = z.object({
NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
DATABASE_URL: z.string().url(),
STRIPE_SECRET_KEY: z.string().startsWith("sk_"),
API_TIMEOUT_MS: z.coerce.number().int().positive().default(5000),
});
export type Env = z.infer<typeof serverSchema>;
function loadEnv(): Env {
const parsed = serverSchema.safeParse(process.env);
if (parsed.success) return parsed.data;
// Escape hatch for `next build` only, where server secrets are not available yet.
if (process.env.SKIP_ENV_VALIDATION === "1") {
return process.env as unknown as Env;
}
const problems = parsed.error.issues
.map((issue) => ` - ${issue.path.join(".")}: ${issue.message}`)
.join("\n");
throw new Error(`Invalid environment variables:\n${problems}`);
}
export const env = loadEnv();With DATABASE_URL unset and a publishable key in STRIPE_SECRET_KEY, the relevant part of the output is:
Error: Invalid environment variables:
- DATABASE_URL: Required
- STRIPE_SECRET_KEY: Invalid input: must start with "sk_"Those messages are from zod 3; newer versions word them differently. Note z.coerce.number(): every environment variable is a string. Import env instead of reading process.env directly and you get typed values too.
Warning:
next buildloads route modules while collecting page data,force-dynamicones included, so this check also runs at build time. A builder withoutDATABASE_URL, like the Docker setup above, fails with these errors.
That is what the SKIP_ENV_VALIDATION branch is for (@t3-oss/env-nextjs, which packages this whole pattern, calls it skipValidation). Set the flag in the builder stage only; the runner stage starts fresh, so the server still validates:
ARG NEXT_PUBLIC_API_URL
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
+ENV SKIP_ENV_VALIDATION=1
RUN npm run buildPublic variables need their own schema that names each key explicitly, for the inlining reason above. This version keeps the earlier publicEnv shape:
// lib/public-env.ts
import { z } from "zod";
const publicSchema = z.object({
NEXT_PUBLIC_SITE_URL: z.string().url(),
NEXT_PUBLIC_DOCS_URL: z.string().url(),
NEXT_PUBLIC_API_URL: z.string().url(),
});
// List every key explicitly so the bundler can inline each one.
const parsed = publicSchema.parse({
NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL,
NEXT_PUBLIC_DOCS_URL: process.env.NEXT_PUBLIC_DOCS_URL,
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
});
// Same shape as the earlier version, so existing imports keep working.
export const publicEnv = {
siteUrl: parsed.NEXT_PUBLIC_SITE_URL,
docsUrl: parsed.NEXT_PUBLIC_DOCS_URL,
apiUrl: parsed.NEXT_PUBLIC_API_URL,
} as const;In Next 14, next start loads a route module on its first request, so a bad deploy looks healthy until then. To validate at boot, load the schema from instrumentation.ts:
// instrumentation.ts
export async function register() {
if (process.env.NEXT_RUNTIME === "nodejs") {
await import("./lib/env");
}
}In Next 14 this file needs experimental.instrumentationHook; in Next 15 it is stable. When I started a Next 14 build with missing variables, the errors were logged at startup and requests got 500s while the process kept running, so watch logs or health checks.
Checklist
- Client code reads it? It needs the
NEXT_PUBLIC_prefix. - Written as
process.env.NEXT_PUBLIC_NAME, with no computed keys, helpers or destructuring? - Did it exist when
next buildran, in that environment (Production vs Preview on Vercel)? - Redeployed after changing it? Grep
.next/staticto see which value was baked in. - Reading a
NEXT_PUBLIC_variable on the server and expecting a runtime value? It is inlined at build time there too. - Is the page or GET handler static? Check the route table, then use
force-dynamic,unstable_noStore()(Next 14) orconnection()(Next 15+). - In Docker, are public values build args, or served at runtime?
- Is
.env.localout of git and the Docker build context? - Which
.envfile wins in this mode, and does a real environment variable override it? - In Turborepo, is the variable declared in
turbo.json, with.envfiles in the task inputs? - Are secrets unprefixed, behind
server-only, and absent from.next/static? - Is env validated at startup, and skipped only during the build?