Explain it simply
Environment variables in plain language
Environment variables are settings handed to the app from outside its code: the database address, a payment key, the app's name. They are not written into the code, so the same code can run on your laptop and on the production server with different settings.
In Next.js, the NEXT_PUBLIC_ prefix is like printing the setting on a public poster: every visitor's browser gets its own copy. Nothing secret may ever wear that prefix.
Problem → Why → Solution
The problem: a secret renamed so the browser can see it
A developer reads process.env.STRIPE_SECRET_KEY in a Client Component and gets undefined in the browser. A quick search says 'add the NEXT_PUBLIC_ prefix', so they rename it, and it works. Now the secret key sits as plain text in the site's JavaScript, and anyone who opens devtools can copy it and issue refunds or read customer data with your account. Meanwhile DATABASE_URL was never set in production, so a confusing connection error only appears at the first query.
"use client";
// renamed so the browser can "see" it, and now everyone can
const stripe = new Stripe(process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY!);The prefix does not grant access; it publishes
NEXT_PUBLIC_ does not mean 'let the browser read it'; it means 'copy this value into the bundle and send it to everyone'. If the browser seems to need a secret, the design is wrong: move the work that uses the secret to the server, in a Server Action or Route Handler.
Core concept: server variables, public variables and build time
Next.js loads .env files into process.env automatically. The lookup order is process.env (set by the shell or the host), .env.$(NODE_ENV).local, .env.local, .env.$(NODE_ENV) and then .env; the first value found wins. When NODE_ENV is test, .env.local is skipped so tests give everyone the same results. Variables without a prefix can only be read by server code (Server Components, Route Handlers, Server Actions), at runtime.
NEXT_PUBLIC_ variables are treated differently at next build: every process.env.NEXT_PUBLIC_X reference in the browser bundle is replaced with the literal string value. That has three consequences. First, anyone can read it. Second, changing the value on your host after the build has no effect in the browser until you rebuild. Third, dynamic lookups such as process.env[name] are not inlined and stay undefined in the browser. A variable without the prefix is likewise undefined in the browser bundle.
Finding out about a missing variable when the app first touches its configuration beats finding out at the first query. Parse process.env with a schema inside one lib/env.ts, put the names of invalid keys in the error message, and never print the values to the log. Server code then imports the typed env object instead of reading process.env directly.
When the browser genuinely needs a value, NEXT_PUBLIC_ is not the only route. A Server Component can read a server variable and deliberately pass it to a Client Component as a prop. That value is read at request time, so no rebuild is needed, and the code shows clearly which value is being exposed.
| File | Commit it? | Purpose |
|---|---|---|
| .env.local | never | real secrets on your machine |
| .env.example | yes | key names with empty or fake values |
| Hosting settings | not in Git | real production values |
- Where is the value used?
- Server only: no prefix, runtime
- Browser too: NEXT_PUBLIC_, public
- Validate all of them early
- Real values in host, not in Git
When in doubt, leave the prefix off. If the browser truly needs it, an undefined will tell you; a leaked secret gives no warning at all.
General pattern
// server code only (Server Component, Route Handler, Server Action)
const secret = process.env.SECRET_NAME; // read at runtime, never sent
// any code, including "use client" components
const publicValue = process.env.NEXT_PUBLIC_NAME; // inlined at build time
// not inlined: dynamic lookups stay undefined in the browser
const missing = process.env[`NEXT_PUBLIC_${name}`];Read secrets without a prefix, in server code only. When reading a NEXT_PUBLIC_ value, write the full name literally, because only that form is inlined by the build.
Worked example: a typed lib/env.ts
Rather than checking a single variable such as DATABASE_URL, this code checks every variable at once with a zod schema, lists every invalid key name in the error message, and exports a typed env object. The .env file itself is not TypeScript, so the matching .env.example file is shown separately in the deeper section below.
// lib/env.ts
import "server-only";
import { z } from "zod";
const ServerEnv = z.object({
DATABASE_URL: z.string().startsWith("postgres://"),
SESSION_SECRET: z.string().min(32),
NEXT_PUBLIC_APP_NAME: z.string().default("Myanmar Notes"),
});
const parsed = ServerEnv.safeParse(process.env);
if (!parsed.success) {
const keys = parsed.error.issues.map((issue) => issue.path.join("."));
throw new Error(`Invalid environment variables: ${keys.join(", ")}`);
}
export const env = parsed.data;
// usage in server code (a Server Component, Route Handler or Server Action):
// import { env } from "@/lib/env";
// const pool = createPool(env.DATABASE_URL);Code breakdown
- Server-only guard
import "server-only";If a Client Component imports this file the build fails, so DATABASE_URL and SESSION_SECRET have no path into the bundle.
- Rules, not just presence
SESSION_SECRET: z.string().min(32),Being present is not enough: a short secret such as "changeme" is rejected too, and DATABASE_URL must start with postgres://.
- A safe default for a public value
NEXT_PUBLIC_APP_NAME: z.string().default("Myanmar Notes"),Harmless public settings can have defaults; secrets never should.
- Names in the error, never values
const keys = parsed.error.issues.map((issue) => issue.path.join("."));The message lists key names only, never values, so the logs cannot leak a secret.
With DATABASE_URL missing, the first server code to import lib/env.ts fails with Invalid environment variables: DATABASE_URL. With everything set, server code uses a typed env.DATABASE_URL, and Client Components cannot import the file at all..env.example and the security baseline
A new team member clones the repo, copies .env.example to .env.local and fills in the values. The file holds key names and comments only, never a real secret. Check that .gitignore ignores .env* files (the create-next-app template usually does) and commit .env.example as the deliberate exception.
# Server only - never prefix these with NEXT_PUBLIC_
DATABASE_URL=postgres://user:password@localhost:5432/notes
SESSION_SECRET=generate-at-least-32-random-characters
# Public - inlined into the browser bundle at build time
NEXT_PUBLIC_APP_NAME=Myanmar Notes| Risk | Baseline defence in a Next.js app |
|---|---|
| Bad input | schema validation in every action and Route Handler |
| XSS | React escapes output; avoid dangerouslySetInnerHTML |
| Clickjacking, sniffing | security headers via headers() in next.config |
| Script injection | a Content-Security-Policy; see the docs for nonces |
| Vulnerable libraries | keep next and dependencies patched; npm audit |
In real projects
In real projects
In production, secrets live in the environment settings of Vercel, Docker or the cloud provider, or in a secret manager, with separate values per environment (development, preview, production). A preview deploy should never touch the production database.
- CI pipelines run validation like lib/env.ts before building and stop the deploy when a variable is missing.
- When a secret leaks, teams rotate the key immediately rather than only deleting it from Git history, because copies may already exist.
- Tools such as Dependabot or Renovate open pull requests automatically for security releases of the next package.
- Only genuinely public values such as an analytics id get NEXT_PUBLIC_, and code review questions every new prefix.
Common mistakes
Common environment and security mistakes
Putting a secret key behind NEXT_PUBLIC_
The moment you add the prefix, the value lands in a JavaScript file as plain text. Move the work that needs the secret into a Server Action or Route Handler and give the browser only the result.
Committing .env.local to Git
Even in a private repo, everyone who clones it and every CI log gets the secret. If it happens, deleting the file is not enough, because it stays in history; rotate the keys.
Changing a NEXT_PUBLIC_ value after the build
The old value was written into the browser bundle at build time, so a restart does not change it; you must rebuild. Watch for this when one Docker image is promoted across several environments.
Printing secret values in error messages
Logging the whole of process.env when validation fails shows every secret to anyone with access to the log service. Show key names only.
Best practices
Best practices
- Import the validated env object instead of reading process.env all over server code.
- Use different secrets for each environment: development, preview and production.
- For every new NEXT_PUBLIC_ variable, ask whether it would be fine posted on the internet.
- Watch security releases of the next package and apply patch versions promptly.
Mini challenge
Mini challenge: an env checker
Write checkEnv, which inspects an environment object and returns a list of problems, and publicValues, which shows what would end up in the browser bundle. Pass a fake object instead of process.env so the output is deterministic.
- Warn that a key starting with NEXT_PUBLIC_ and containing SECRET, PASSWORD, PRIVATE or TOKEN would be sent to the browser
- Check DATABASE_URL (starts with postgres://) and SESSION_SECRET (at least 32 characters) with zod
- Problem messages contain key names only, never values
- publicValues returns only the NEXT_PUBLIC_ keys
import { z } from "zod";
type RawEnv = Record<string, string | undefined>;
const ServerSchema = z.object({
// TODO: DATABASE_URL must start with postgres://
// TODO: SESSION_SECRET needs at least 32 characters
});
const SECRET_WORDS = /SECRET|PASSWORD|PRIVATE|TOKEN/;
function checkEnv(raw: RawEnv): string[] {
// TODO: flag NEXT_PUBLIC_ keys whose names look secret
// TODO: run ServerSchema and turn each issue into "<KEY> is missing or invalid"
}
function publicValues(raw: RawEnv): RawEnv {
// TODO: keep only NEXT_PUBLIC_ keys - this is what the browser would get
}
// TODO: check one healthy env and one broken env, print the resultsExpected: The healthy env prints problems: none and the browser gets only NEXT_PUBLIC_APP_NAME. The broken env prints three problems (the NEXT_PUBLIC_STRIPE_SECRET_KEY warning, DATABASE_URL and SESSION_SECRET) and shows the browser would receive the secret key.
Show hint
Filter Object.entries and rebuild with Object.fromEntries. The first element of each zod issue's path is the key name.
Show solution
import { z } from "zod";
type RawEnv = Record<string, string | undefined>;
const ServerSchema = z.object({
DATABASE_URL: z.string().startsWith("postgres://"),
SESSION_SECRET: z.string().min(32),
});
const SECRET_WORDS = /SECRET|PASSWORD|PRIVATE|TOKEN/;
function checkEnv(raw: RawEnv): string[] {
const problems: string[] = [];
for (const key of Object.keys(raw)) {
if (key.startsWith("NEXT_PUBLIC_") && SECRET_WORDS.test(key)) {
problems.push(`${key} looks secret but would be sent to the browser`);
}
}
const result = ServerSchema.safeParse(raw);
if (!result.success) {
for (const issue of result.error.issues) {
problems.push(`${String(issue.path[0])} is missing or invalid`);
}
}
return problems;
}
function publicValues(raw: RawEnv): RawEnv {
return Object.fromEntries(
Object.entries(raw).filter(([key]) => key.startsWith("NEXT_PUBLIC_")),
);
}
const healthy: RawEnv = {
DATABASE_URL: "postgres://app:pw@db:5432/notes",
SESSION_SECRET: "x".repeat(40),
NEXT_PUBLIC_APP_NAME: "Myanmar Notes",
};
const broken: RawEnv = {
SESSION_SECRET: "changeme",
NEXT_PUBLIC_APP_NAME: "Myanmar Notes",
NEXT_PUBLIC_STRIPE_SECRET_KEY: "sk_live_123",
};
for (const [name, env] of [["healthy", healthy], ["broken", broken]] as const) {
const problems = checkEnv(env);
const summary = problems.length ? `${problems.length} problems` : "problems: none";
console.log(`${name}: ${summary}`);
for (const p of problems) console.log(" -", p);
console.log(" browser gets:", Object.keys(publicValues(env)).join(", "));
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Variables without a prefix are readable only by server code at runtime, and that is where secrets belong.
- NEXT_PUBLIC_ values are inlined into the browser bundle at next build, readable by anyone, and need a rebuild to change.
- Validate variables with a schema in one place such as lib/env.ts, and show only key names in errors.
- Never commit .env.local; commit .env.example, and rotate any key that leaks.
- Baseline: input validation, React's escaping, security headers, CSP, HTTPS and dependency updates.
Next.js — Environment Variables — Next.js
Next.js — Environment Variables — Next.js