---
title: "Environment Variables in Next.js"
url: https://www.khanwaseem.com/blog/nextjs-tutorial/environment-variables-in-next-js
author: "khan Waseem"
published: 2026-12-01
updated: 2026-12-01
topics: ["Nextjs Tutorial", "course"]
description: "How environment variables work in Next.js 16: .env, .env.local and per-environment files, load order, server-only secrets vs NEXT_PUBLIC_ variables, why public values are frozen at build time, validation, and setting…"
---

# Environment Variables in Next.js

Table of Contents

[Toggle](#)

- [Introduction:](#introduction)
- [Part 1: The .env Files](#part-1-the-env-files)[1. What Is a .env File?:](#1-what-is-a-env-file)
- [2. The Different .env Files:](#2-the-different-env-files)
- [3. Which Value Wins? (Load Order):](#3-which-value-wins-load-order)
- [4. Keep Secrets Out of Git:](#4-keep-secrets-out-of-git)

- [Part 2: Server Variables vs Public Variables](#part-2-server-variables-vs-public-variables)[5. Server-Only by Default:](#5-server-only-by-default)
- [6. NEXT_PUBLIC_ Variables in the Browser:](#6-next-public-variables-in-the-browser)
- [7. How NEXT_PUBLIC_ Works: Inlined at Build Time:](#7-how-next-public-works-inlined-at-build-time)
- [8. Build Time vs Runtime:](#8-build-time-vs-runtime)
- [9. Development vs Production Values:](#9-development-vs-production-values)

- [Part 3: Doing It Properly](#part-3-doing-it-properly)[10. Validate Variables at Startup:](#10-validate-variables-at-startup)
- [11. Setting Variables on Vercel:](#11-setting-variables-on-vercel)
- [12. Common Mistakes:](#12-common-mistakes)

- [Conclusion:](#conclusion)

## 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](https://blog.khanwaseem.com/next-js-app-router-and-server-components/) and [deploying to Vercel](https://blog.khanwaseem.com/deploying-next-js-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:

```php
# .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_EMAILCode language: PHP (php)
```

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:

```php
# .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:4000Code language: PHP (php)
```

and two tiny environment-specific files:

```php
# .env.development
NEXT_PUBLIC_API_VERSION=v1-dev

# .env.production
NEXT_PUBLIC_API_VERSION=v2Code language: PHP (php)
```

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

```css
- Environments: .env.local, .env.production, .envCode language: CSS (css)
```

and the dev server printed:

```css
- Environments: .env.local, .env.development, .envCode language: CSS (css)
```

### 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:

- The real environment of the process (for example, a value set in your terminal or on Vercel)

- `.env.$(NODE_ENV).local`

- `.env.local` (skipped when `NODE_ENV` is `test`)

- `.env.$(NODE_ENV)`

- `.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:

```javascript
server API_BASE_URL: http://localhost:4000Code language: JavaScript (javascript)
```

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

```javascript
API_BASE_URL=https://prod-api.example.com npx next startCode language: JavaScript (javascript)
```

and the page showed:

```javascript
server API_BASE_URL: https://prod-api.example.comCode language: JavaScript (javascript)
```

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`:

```css
# env files
.env*Code language: CSS (css)
```

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:

```php
# .env.example (committed): copy to .env.local and fill in
DATABASE_URL=
STRIPE_SECRET_KEY=Code language: PHP (php)
```

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:

```javascript
// 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>
  );
}Code language: JavaScript (javascript)
```

The page showed:

```php
server DATABASE_URL set: true
server API_BASE_URL: http://localhost:4000
server CONTACT_LINE: Write to support@example.comCode language: PHP (php)
```

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_`**:

```javascript
// 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>;
}Code language: JavaScript (javascript)
```

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

```json
{"site":"Khan Shop","version":"v2","secret":"undefined"}Code language: JSON / JSON with Comments (json)
```

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`:

```javascript
files containing "Khan Shop":          1
files containing the Stripe secret:    0
files containing the database password: 0Code language: JavaScript (javascript)
```

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:

```javascript
server NEXT_PUBLIC_API_VERSION: v2
server RUNTIME_FLAG: on
client version: "v2"Code language: JavaScript (javascript)
```

- `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:

```javascript
server NEXT_PUBLIC_API_VERSION: v1-dev
{"site":"Khan Shop","version":"v1-dev","secret":"undefined"}Code language: JavaScript (javascript)
```

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:

```javascript
// 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",
};Code language: JavaScript (javascript)
```

Running the same check with `STRIPE_SECRET_KEY` missing gives:

```javascript
Error: Missing environment variable: STRIPE_SECRET_KEYCode language: JavaScript (javascript)
```

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](https://blog.khanwaseem.com/api-routes-in-next-js/)) 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.

### Related posts:

[Deploying a Next.js App to Vercel](https://blog.khanwaseem.com/deploying-next-js-to-vercel/)
[CSS – Custom Properties (Variables)](https://blog.khanwaseem.com/css-custom-properties-variables/)
[API Routes in Next.js](https://blog.khanwaseem.com/api-routes-in-next-js/)
[Next.js App Router and Server Components](https://blog.khanwaseem.com/next-js-app-router-and-server-components/)

Powered by [YARPP](https://yarpp.com).
