Skip to content
Frameworks

Next.js environment variables: NEXT_PUBLIC_, .env.local and runtime config

Next.js loads environment variables from .env files automatically: .env.local overrides .env, and mode files such as .env.development apply to next dev or next build. Variables are server-only by default; only names that start with NEXT_PUBLIC_ reach the browser, and those are inlined into the JavaScript bundle when you run next build, so changing them later needs a rebuild. Server code that renders dynamically can read any variable at request time, which is how one build can be deployed to several environments.

Published 6 min read By the ProductEnv team

Which .env files does Next.js load, and in what order?

Next.js reads up to four files from the project root and merges them into process.env. When the same name appears in several places, the first one in this list wins:

  1. Variables already set in the real environment, for example by your shell, Docker or the hosting platform.
  2. .env.$(NODE_ENV).local, such as .env.development.local.
  3. .env.local, skipped when NODE_ENV is test so tests behave the same on every machine.
  4. .env.$(NODE_ENV), such as .env.production.
  5. .env, the shared defaults.

NODE_ENV is set for you: next dev uses development, while next build and next start use production. The convention that follows is simple. Commit .env and .env.development only if they hold safe defaults, keep personal and secret values in .env.local, and git-ignore every .local file. Values can also reference each other with $NAME, and a literal dollar sign is written \$.

.env.local
# Server-only: never reaches the browser
DATABASE_URL=postgres://app:app@localhost:5432/store
STRIPE_SECRET_KEY=sk_test_51Hx0000000000000000

# Public: inlined into the client bundle at build time
NEXT_PUBLIC_SITE_URL=http://localhost:3000
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_51Hx0000000000000000

What does NEXT_PUBLIC_ actually do?

Without the prefix, a variable exists only in Node.js: Server Components, Route Handlers, Server Actions and API routes can read it, and the browser never sees it. With the NEXT_PUBLIC_ prefix, next build searches your client code for process.env.NEXT_PUBLIC_SOMETHING and replaces it with the literal value. The bundle that ships to visitors contains the string itself.

app/checkout/pay-button.tsx
"use client";

// Inlined at build time: the bundle contains the literal "pk_test_..."
const publishableKey = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY;

// NOT inlined: dynamic lookups and destructuring stay undefined in the browser
const name = "NEXT_PUBLIC_SITE_URL";
const broken = process.env[name];
const { NEXT_PUBLIC_SITE_URL } = process.env;

Two consequences catch teams out. First, the value is frozen into the build: change NEXT_PUBLIC_API_URL on your hosting platform and nothing happens until the next build. Second, everything with the prefix is public. A secret key with NEXT_PUBLIC_ in front of it is published to every visitor, and renaming it afterwards doesn't remove it from bundles already cached or deployed.

Rotate anything that was ever public

If a secret was given the NEXT_PUBLIC_ prefix and deployed, treat it as leaked: rotate it at the provider, then move it to a server-only name. Publishable keys meant for browsers, such as a Stripe publishable key or a public analytics ID, are fine with the prefix.

How do you read environment variables at runtime in the App Router?

Server code reads process.env when it runs, but a page that is statically rendered runs during next build, so the value it sees is the one present at build time. To read the value of the environment the app is running in, render the code per request. In recent Next.js versions, awaiting connection() from next/server does that explicitly; reading cookies or headers has the same effect.

app/status/page.tsx
import { connection } from "next/server";

export default async function StatusPage() {
  await connection(); // render per request, not at build time
  const region = process.env.DEPLOY_REGION ?? "unknown";
  return <p>Served from {region}</p>;
}

This is the basis of the build once, deploy many pattern: one Docker image for staging and production, with server-side values injected when the container starts. It works for server-only variables. Client code still needs either a build per environment or a small server endpoint or Server Component that passes the runtime value down as a prop.

To keep secrets from leaking into client code by accident, put the modules that read them behind import "server-only", which makes the build fail if a Client Component imports them. Scripts and test setups that run outside Next.js can load the same files with loadEnvConfig from @next/env. The Next.js environment variables documentation has the details for your version.

How do environment variables work on Vercel?

Hosting platforms don't read your .env files from the repository, and they shouldn't, because those files are git-ignored. On Vercel you set each variable in the project settings and choose which environments it applies to: Production, Preview, Development or a combination. vercel env pull downloads the Development values into a local file, .env.local by default.

  • A change to a NEXT_PUBLIC_ variable needs a new deployment, because the old bundle still holds the old string.
  • Preview deployments should get their own values, never production credentials, since every branch gets a preview.
  • Variables are read at build time and runtime, so a server-only value used in a statically rendered page also needs a redeploy.

The Vercel environment variables documentation lists the current size limits and system variables such as the deployment URL.

What are the most common Next.js environment variable mistakes?

Common Next.js environment variable problems and fixes
SymptomLikely causeFix
undefined in a Client ComponentNo NEXT_PUBLIC_ prefix, or a dynamic lookupAdd the prefix for public values; read it as process.env.NEXT_PUBLIC_X
Old value after changing it on the hostInlined or statically rendered at build timeRedeploy, or render the code per request
Works locally, empty in tests.env.local is skipped when NODE_ENV is testPut test values in .env.test
A teammate's app crashes on startTheir .env.local lacks a key you addedUpdate .env.example and share values from one source
Secret visible in page sourceSecret given the NEXT_PUBLIC_ prefixRotate it, then rename it without the prefix

Validating the environment at startup turns the quiet failures into loud ones. A small module that reads every required variable once, checks it and exports typed values means a missing key fails the build or the first request with a clear message, instead of a blank page three clicks later.

How does a team keep .env.local in sync?

.env.local is personal and git-ignored, which is right for secrets and wrong for coordination: when one developer adds RESEND_API_KEY, nobody else's file has it. The fix is one source of truth that everyone pulls from. With ProductEnv, link the file once and pull it whenever something changes:

Terminal
npx productenv init
npx productenv link development .env.local
npx productenv pull
✅ Pulled 9 secrets from store/development → .env.local
# CI or a script: check for drift without revealing values
npx productenv diff --exit-code

The link lives in .productenv.json, which you commit, so the next developer's pull writes .env.local too. Production values can go straight to Vercel with a deploy integration instead of being typed into its settings, and the VS Code extension shows which environments define each process.env.X your code reads. The guide to keeping .env files in sync covers the workflow in more depth.

Frequently asked questions

Why is process.env undefined in a Next.js Client Component?

Client Components only receive variables whose names start with NEXT_PUBLIC_, and only when read literally as process.env.NEXT_PUBLIC_NAME. Variables without the prefix stay on the server, and dynamic lookups such as process.env[name] are not replaced at build time. Restart next dev after editing a .env file so the new value is picked up.

Should .env.local be committed in a Next.js project?

No. .env.local is meant for secrets and personal overrides, so it belongs in .gitignore. Commit a .env.example with the key names instead, and keep the real values in a secrets manager or your hosting platform.

Can NEXT_PUBLIC_ variables change without rebuilding?

No. They are replaced with their literal values during next build, so the deployed JavaScript contains the old string until you build again. If a client-side value must change per environment without a rebuild, read it on the server at request time and pass it to the client as a prop.

Which .env file does next build use?

next build runs with NODE_ENV set to production, so it loads .env.production.local, .env.local, .env.production and .env, with the real environment taking priority over all of them. Values for staging usually come from the hosting platform rather than a separate file.