Environment Variables in Next.js

By Published 8 min read

Environment Variables in Next.js

Introduction:

Almost every real app needs settings that change from place to place. Your laptop talks to a local database, but production talks to a real one. Your test payments use a Stripe test key, but customers pay with the live key. And some of these values, like database passwords and API secrets, must never be written into your code or pushed to GitHub.

Environment variables solve this. They are named values supplied from outside your code, such as DATABASE_URL or STRIPE_SECRET_KEY. The same code reads them, and each environment (your laptop, a preview deployment, production) supplies its own values.

Next.js has built-in support for environment variables, with a few rules that every Next.js developer must understand, because getting them wrong either breaks your app or leaks your secrets to every visitor. In this lesson we will learn the .env files and their load order, the difference between server-only variables and NEXT_PUBLIC_ variables, why public values are frozen at build time, how to validate variables, and how to set them on Vercel.

This follows our lessons on the App Router and Server Components and deploying to Vercel. Every result below comes from a real Next.js 16.4 app that we built and ran, and the outputs shown are what the browser actually displayed.

Part 1: The .env Files

1. What Is a .env File?:

A .env file is a plain text file of NAME=value lines in the root of your project, next to package.json. When you run next dev, next build or next start, Next.js reads these files and puts the values into process.env, so your code can use them:

# .env
APP_NAME=Khan Shop
API_BASE_URL=https://api.example.com
NEXT_PUBLIC_SITE_NAME=Khan Shop
NEXT_PUBLIC_API_VERSION=v1
SUPPORT_EMAIL=support@example.com
CONTACT_LINE=Write to $SUPPORT_EMAIL

A few format rules:

  • One variable per line, NAME=value, with no spaces around =.
  • Lines starting with # are comments.
  • Wrap values containing spaces or special characters in quotes, for example GREETING="Hello there".
  • You can reference another variable with $NAME. In our app, CONTACT_LINE came out as Write to support@example.com. To use a literal dollar sign, escape it as \$.

2. The Different .env Files:

Next.js looks for several files, each with a different purpose:

  • .env: default values for every environment. Safe to commit, so it must not contain secrets.
  • .env.local: your personal, local overrides and secrets. Never commit it.
  • .env.development: used only by next dev.
  • .env.production: used only by next build and next start.
  • .env.development.local and .env.production.local: local, secret versions of the two above.
  • .env.test: used when NODE_ENV is test (for example in Jest). In test mode, .env.local is not loaded, so tests behave the same for everyone.

Our test app had this .env.local, holding the secrets:

# .env.local  (never committed)
DATABASE_URL=postgres://shop:s3cr3t-pass@localhost:5432/shop
STRIPE_SECRET_KEY=sk_test_SECRET_123
API_BASE_URL=http://localhost:4000

and two tiny environment-specific files:

# .env.development
NEXT_PUBLIC_API_VERSION=v1-dev

# .env.production
NEXT_PUBLIC_API_VERSION=v2

Next.js prints which files it loaded when it starts. Our build printed:

- Environments: .env.local, .env.production, .env

and the dev server printed:

- Environments: .env.local, .env.development, .env

3. Which Value Wins? (Load Order):

When the same variable is defined in several places, Next.js uses the first one it finds, in this order:

  1. The real environment of the process (for example, a value set in your terminal or on Vercel)
  2. .env.$(NODE_ENV).local
  3. .env.local (skipped when NODE_ENV is test)
  4. .env.$(NODE_ENV)
  5. .env

We can see this in our app. API_BASE_URL is https://api.example.com in .env but http://localhost:4000 in .env.local, and the page showed the local one:

server API_BASE_URL: http://localhost:4000

Then we started the production server with a real environment variable set in the terminal:

API_BASE_URL=https://prod-api.example.com npx next start

and the page showed:

server API_BASE_URL: https://prod-api.example.com

A real environment variable beats every file. This is exactly how hosting platforms like Vercel work: you don’t upload .env.local; the platform provides the variables directly to the process.

4. Keep Secrets Out of Git:

The most important rule: files containing secrets must never be committed. A secret pushed to GitHub, even for a minute in a public repository, should be considered stolen; bots scan GitHub for keys constantly.

create-next-app already adds this to .gitignore:

# env files
.env*

That ignores all env files. Many teams prefer to commit a .env (or a .env.example) with safe defaults and placeholder names, so new developers know which variables they need:

# .env.example (committed): copy to .env.local and fill in
DATABASE_URL=
STRIPE_SECRET_KEY=

If you do this, change the .gitignore rule to .env*.local so only the local files stay ignored.

Part 2: Server Variables vs Public Variables

5. Server-Only by Default:

By default, an environment variable is available only on the server: in Server Components, Route Handlers, Server Actions, middleware and next.config.js. That’s exactly where secrets belong.

Here is a Server Component reading our variables:

// app/page.js  (a Server Component)
import ClientInfo from "./client-info";

export const dynamic = "force-dynamic";

export default function Page() {
  return (
    <main>
      <p>server DATABASE_URL set: {String(Boolean(process.env.DATABASE_URL))}</p>
      <p>server API_BASE_URL: {process.env.API_BASE_URL}</p>
      <p>server CONTACT_LINE: {process.env.CONTACT_LINE}</p>
      <ClientInfo />
    </main>
  );
}

The page showed:

server DATABASE_URL set: true
server API_BASE_URL: http://localhost:4000
server CONTACT_LINE: Write to support@example.com

Notice we printed whether DATABASE_URL is set, not its value. Never render a secret into the HTML, even from the server; anything in the HTML is visible to the visitor.

6. NEXT_PUBLIC_ Variables in the Browser:

Code that runs in the browser (Client Components marked "use client") cannot read the server’s environment. If you need a value in the browser, such as an analytics ID, a public API URL or a site name, give the variable the prefix NEXT_PUBLIC_:

// app/client-info.js
"use client";
import { useEffect, useState } from "react";

export default function ClientInfo() {
  const [info, setInfo] = useState(null);

  useEffect(() => {
    setInfo({
      site: process.env.NEXT_PUBLIC_SITE_NAME,
      version: process.env.NEXT_PUBLIC_API_VERSION,
      secret: String(process.env.STRIPE_SECRET_KEY),
    });
  }, []);

  return <pre>{JSON.stringify(info)}</pre>;
}

We read the values inside useEffect, which only runs in the browser, so we know this is truly client-side. The browser displayed:

{"site":"Khan Shop","version":"v2","secret":"undefined"}

The public variables arrived, and the secret is undefined, exactly as it should be. Next.js refused to send STRIPE_SECRET_KEY to the browser because it has no NEXT_PUBLIC_ prefix.

7. How NEXT_PUBLIC_ Works: Inlined at Build Time:

The browser has no process.env. So how did the value get there? During next build, Next.js finds every process.env.NEXT_PUBLIC_... in your code and replaces it with the actual text value. After the build, the JavaScript file sent to the browser literally contains "Khan Shop", not a variable lookup.

We checked the built browser files in .next/static:

files containing "Khan Shop":          1
files containing the Stripe secret:    0
files containing the database password: 0

This has two big consequences:

  • Anything with NEXT_PUBLIC_ is public. Anyone can open your site’s JavaScript and read it. Never put a secret in a NEXT_PUBLIC_ variable, no matter how convenient it seems. Publishable keys (like a Stripe *publishable* key or a Firebase web config) are designed to be public; secret keys are not.
  • Public values are frozen when you build. Changing them later has no effect until you build again (next section).

Because the replacement looks for the exact text process.env.NEXT_PUBLIC_NAME, always write the full name directly. Don’t destructure (const { NEXT_PUBLIC_X } = process.env) or build the name dynamically; the Next.js documentation says those patterns are not guaranteed to be inlined.

8. Build Time vs Runtime:

Let’s prove the freezing. Our app was built with .env.production setting NEXT_PUBLIC_API_VERSION=v2. Then we started it with a different value, plus a brand new server variable:

RUNTIME_FLAG=on NEXT_PUBLIC_API_VERSION=v9 npx next start

The page showed:

server NEXT_PUBLIC_API_VERSION: v2
server RUNTIME_FLAG: on
client version: "v2"
  • NEXT_PUBLIC_API_VERSION stayed v2, both in the browser and on the server, because it was inlined during the build. The v9 we passed at start-up was ignored.
  • RUNTIME_FLAG, a normal server variable, was read at runtime, so the new value appeared without rebuilding. (This works here because the page is dynamic. A page that is prerendered as static HTML during the build bakes in whatever values it read at build time.)

In practice this means:

  • If you change a NEXT_PUBLIC_ variable on Vercel, you must redeploy for it to take effect.
  • If you build one Docker image and want to run it in staging and production with different public values, NEXT_PUBLIC_ variables won’t work. Instead, read a normal server variable in a Server Component and pass it down to Client Components as a prop.

9. Development vs Production Values:

The environment-specific files let the same code use different values automatically. With next dev, our page showed the development value:

server NEXT_PUBLIC_API_VERSION: v1-dev
{"site":"Khan Shop","version":"v1-dev","secret":"undefined"}

and the production build showed v2. Note that NODE_ENV is set by Next.js itself (development for next dev, production for next build and next start); you shouldn’t set it yourself in .env files.

Part 3: Doing It Properly

10. Validate Variables at Startup:

A missing variable usually doesn’t fail loudly. process.env.DATABASE_URL is just undefined, and the app crashes later with a confusing error, often in production. It’s much better to check all required variables in one place and fail immediately with a clear message:

// lib/env.js
import "server-only";

function required(name) {
  const value = process.env[name];
  if (!value) throw new Error(`Missing environment variable: ${name}`);
  return value;
}

export const env = {
  databaseUrl: required("DATABASE_URL"),
  stripeSecretKey: required("STRIPE_SECRET_KEY"),
  apiBaseUrl: process.env.API_BASE_URL ?? "http://localhost:4000",
};

Running the same check with STRIPE_SECRET_KEY missing gives:

Error: Missing environment variable: STRIPE_SECRET_KEY

Now the rest of your code imports env.databaseUrl instead of reading process.env everywhere, which also gives you one list of every variable the app needs. Many projects use a schema library such as Zod for this, which can also check formats (for example, that a value is a valid URL).

The import "server-only" line is a safety net: if anyone ever imports this file from a Client Component, the build fails instead of quietly trying to bundle server code for the browser. (Dynamic lookups like process.env[name] are fine here, because this file only runs on the server, where process.env is real.)

11. Setting Variables on Vercel:

On Vercel, you don’t upload .env.local. Instead, open your project, go to Settings → Environment Variables, and add each variable. Each one can be enabled for:

  • Production: your live site, built from the main branch.
  • Preview: deployments for other branches and pull requests. Point these at a test database and test API keys.
  • Development: values you can download to your laptop with the Vercel CLI (vercel env pull .env.local).

Remember the rule from section 8: after changing a variable, redeploy, because builds read the values at build time. Vercel also provides useful system variables automatically, such as VERCEL_ENV (production, preview or development) and VERCEL_URL.

12. Common Mistakes:

  • Putting a secret in NEXT_PUBLIC_. It is shipped to every visitor’s browser. If this has happened, rotate the key (create a new one and delete the old one); removing it from the code isn’t enough.
  • Committing .env.local. Same fix: rotate every secret it contained, then remove the file from git and fix .gitignore.
  • Expecting a new value without rebuilding. NEXT_PUBLIC_ values and statically rendered pages only change after a new build.
  • Reading a server variable in a Client Component and getting undefined. Either it is a secret (keep it on the server, maybe behind a Route Handler) or it is truly public (rename it with NEXT_PUBLIC_).
  • Spaces around = or unquoted values with spaces and #. Quote values when in doubt.
  • Forgetting to restart the dev server. .env files are read at start-up. If a change doesn’t show, stop and restart next dev.

Conclusion:

Environment variables let one codebase run with different settings and secrets in every environment. Next.js loads them from .env, .env.local and the per-environment files, with real environment variables winning over all files. By default variables exist only on the server, which keeps secrets safe. Variables prefixed with NEXT_PUBLIC_ are copied into the browser bundle at build time: we saw them arrive in the browser, saw the Stripe secret correctly stay undefined, and saw a public value stay frozen at v2 even when we started the server with v9. Finally, we validated variables at start-up and set them up on Vercel.

In the next lesson we will learn Server Actions in Next.js, which let forms and buttons run secure server code, where these environment variables live, without writing a separate API.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume