Skip to content
BackendChapter 22 / 34Beginner4 min read

Environment Variables

How to keep Next.js environment variables in .env files, what the NEXT_PUBLIC_ prefix means, and how to keep server secrets away from the browser.

On this page

1. What are environment variables?

A database URL, API keys, a payment secret and the site URL are all different in every environment: your machine, staging and production. Hardcoding them in the code is dangerous and painful.

Next.js loads .env files by itself. You do not need any extra package.

2. Why does it matter?

Hardcoded valuesEnvironment variables
The API key gets committed to GitThe secret stays only in .env.local or on the platform
Change the code for every environmentThe same code, different values
If a key leaks, you have to clean the whole historyJust rotate the value
A secret can reach the browserVariables without NEXT_PUBLIC_ stay on the server

3. Where is it used?

VariableWhere it is neededPrefix
DATABASE_URLServer onlyNone
AUTH_SECRETServer onlyNone
STRIPE_SECRET_KEYServer onlyNone
NEXT_PUBLIC_SITE_URLServer and browserNEXT_PUBLIC_
NEXT_PUBLIC_ANALYTICS_IDBrowser scriptNEXT_PUBLIC_

4. How does it work?

The journey of an env variable
.env files are loaded
Server code reads from process.env
At next build, NEXT_PUBLIC_ values are inlined into the JS bundle
The browser gets only the NEXT_PUBLIC_ values

Files and priority

Next.js looks for values in these places, and the first match wins:

OrderSource
1process.env (set in the platform or the shell)
2.env.development.local or .env.production.local
3.env.local (not loaded in the test environment)
4.env.development or .env.production
5.env

.env*.local files are for secrets and are not committed to Git. Keep only safe defaults in .env.

5. Code example

Step 1: the .env.local file

bash
DATABASE_URL="postgresql://user:password@localhost:5432/shop"
AUTH_SECRET="value-generated-with-openssl-rand-base64-32"
NEXT_PUBLIC_SITE_URL="http://localhost:3000"

Step 2: validate and use on the server

ts
import "server-only";
import * as z from "zod";

const EnvSchema = z.object({
  DATABASE_URL: z.url(),
  AUTH_SECRET: z.string().min(32),
});

export const env = EnvSchema.parse({
  DATABASE_URL: process.env.DATABASE_URL,
  AUTH_SECRET: process.env.AUTH_SECRET,
});

Step 3: a public variable in a Client Component

tsx
"use client";

export function ShareButton({ path }: { path: string }) {
  const url = `${process.env.NEXT_PUBLIC_SITE_URL}${path}`;
  return <button onClick={() => navigator.clipboard.writeText(url)}>Copy link</button>;
}

How does the code work?

PartMeaning
.env.localLocal secrets, in the Git ignore list
import "server-only"The build fails if this file is imported into a Client Component by mistake
EnvSchema.parse(...)Catches a missing or wrong variable as soon as the app starts
process.env.NEXT_PUBLIC_SITE_URLReplaced with the real string at build time
AUTH_SECRET in the clientYou get undefined, it never reaches the browser

NEXT_PUBLIC_ values are frozen at build time. After you change the value, you must run next build again. Server side variables are read at request time in dynamic rendering.

Interview tip

"Why does process.env[key] not work on the client?" Answer: Next.js only replaces a directly written process.env.NEXT_PUBLIC_X at build time. A dynamic lookup is not inlined.

6. Common mistakes

Mistake: Adding the NEXT_PUBLIC_ prefix to a secret key

Why? The value goes into the JavaScript bundle and anyone can see it in the browser.

Better: Keep secrets without the prefix and use them only in server code.

Mistake: Committing .env.local to Git

Why? Database passwords and API keys leak into a public repo.

Better: Keep .env*.local in .gitignore and write only the names in .env.example.

Mistake: Changing a NEXT_PUBLIC_ value in production without rebuilding

Why? Public values are inlined at build time, so the old value keeps running.

Better: After changing a public variable, create a new build and deploy.

Mistake: Not finding out about a missing variable until runtime

Why? The app keeps running and then crashes strangely on the first request.

Better: Validate env with Zod at startup so the mistake is seen immediately.

7. What to learn before and after

Final quick revision

PointDetail
Readingprocess.env.NAME
For the browserThe NEXT_PUBLIC_ prefix, inlined at build time
SecretsNo prefix, server only
Local secrets.env.local, not in Git
Safetyserver-only + Zod validation