Environment Variables Explained: A Practical Guide
How environment variables work across shells and platforms, why .env files leak secrets, and the configuration rules that keep deployments predictable.
By Velloreth
What an environment variable really is
An environment variable is a named value stored in a process’s environment block — a small set of key-value strings the operating system hands to a process when it starts. Every process gets one, and every child process inherits a copy of its parent’s.
That inheritance is the whole mechanism, and it explains nearly every confusing behaviour people hit:
- Setting a variable in a terminal affects only processes started from that terminal afterwards.
- A server started before you exported the variable never sees it.
- A variable set inside a script is invisible to the shell that ran the script, because the child cannot modify the parent.
- A long-running process keeps the environment it started with, even if you change the variable later.
So the correct mental model is not “global settings.” It is “a snapshot of configuration passed down a process tree at spawn time.”
Why configuration lives in the environment at all
The core argument comes from the Twelve-Factor App methodology, and it is worth stating plainly: code should not know where it is running. The same build artifact should run in development, staging, and production, with only the environment differing.
Concretely, that means these all belong in the environment:
- Database connection strings and hosts.
- API base URLs and third-party endpoints.
- Feature flags and log levels.
- Ports and timeouts.
- Credentials — with the caveat below.
And these do not:
- Anything that changes code behaviour structurally.
- Business logic constants that should be reviewed like code.
- Values that differ between two callers within the same deployment.
A useful test: would I want to change this without rebuilding? If yes, it is configuration. If changing it should require a review, keep it in code.
The .env file, and the trap inside it
The .env file is the most misunderstood part of this whole topic, so let’s be precise about what it is.
A .env file is a plain text file. It is not a standard, not an OS feature, and not understood by your application by default. A library — dotenv in Node, python-dotenv in Python, built-in support in Vite, Next.js, Astro, and most modern frameworks — reads the file at startup and copies the values into process.env or its equivalent.
That distinction matters because it tells you the file’s real role: local development convenience. It exists so a new developer can run the project without hand-exporting fifteen variables.
The trap is that the same mechanism is often used for deployment, where it is a liability.
# .env — NEVER commit this file
DATABASE_URL=postgres://user:pass@localhost:5432/app
STRIPE_SECRET_KEY=sk_live_...
Rule one: .env goes in .gitignore, on the first commit, before any secret is ever added. A secret committed once is compromised even after you delete it — it lives in git history, in forks, in clones, and in whatever scraped the repo. Rotation is the only remedy.
Rule two: .env.example is the committed file. Same keys, no values, with a comment on each. This is how a new developer knows what to set without any secret entering the repository.
Rule three: never load .env in production. Production configuration should come from the platform — the container orchestrator, the CI secret store, the host’s systemd unit, or the PaaS dashboard. A .env file on a production server is a file that can be read, copied, and accidentally included in a backup.
If your repository already has a committed .env, treat every credential in it as leaked and rotate. How to create an SSH key and add it to GitHub covers the same “secret handling” discipline for git credentials specifically, and deploying apps with Docker Compose shows the runtime-injection side of it.
Setting variables on each platform
The syntax differs enough that it is worth having in one place.
macOS / Linux, current session only:
export API_URL="https://api.example.com"
node server.js # inherits API_URL
macOS / Linux, single command only — the variable exists for that one process and is gone afterwards:
API_URL="https://api.example.com" node server.js
This form is genuinely useful and underused: it scopes the override to exactly one run, so it cannot leak into your next command.
Persistent, for interactive shells — add the export line to ~/.zshrc (macOS default) or ~/.bashrc (most Linux distros), then source the file or open a new terminal.
systemd services — do not put the variable in your shell profile, because services do not read it:
[Service]
Environment="API_URL=https://api.example.com"
EnvironmentFile=/etc/myapp/env
Windows, current session: set API_URL=https://api.example.com
Windows, persistent: setx API_URL "https://api.example.com" — note that setx affects future shells, not the current one, which catches people out.
Docker: -e API_URL=... on the command line, env_file: in Compose, or ENV in a Dockerfile — but never ENV for secrets, because Dockerfile layers are inspectable even if you later unset the value.
CI platforms: every major one has a secrets store — GitHub Actions secrets, GitLab CI variables, CircleCI contexts. Use it, and they arrive as environment variables at runtime.
One important cross-platform difference: Windows environment variable names are case-insensitive; Linux and macOS are case-sensitive. API_URL and api_url are the same variable on Windows and two different variables everywhere else. This is a classic source of “it works on my machine.”
Everything is a string
This is the single most common bug with environment variables, and it is not obvious until it bites you.
// WRONG — this is always truthy
if (process.env.DEBUG) {
enableVerboseLogging();
}
process.env.DEBUG = "false" is a non-empty string, and a non-empty string is truthy in JavaScript. So DEBUG=false enables debug mode. The same class of bug makes PORT=0 behave oddly and makes MAX_RETRIES="3" fail arithmetic in languages that do not coerce.
The fix is to parse and validate explicitly, once, at startup:
const DEBUG = process.env.DEBUG === 'true';
const PORT = Number.parseInt(process.env.PORT ?? '3000', 10);
if (!Number.isInteger(PORT)) throw new Error('PORT must be an integer');
Never scatter Number.parseInt(process.env.X) through the codebase. Convert once at the boundary and pass typed values inward.
Validate at startup, not at first use
The difference between a good and a bad configuration setup is when a missing value is discovered.
Bad: the server boots fine and fails three hours later when someone first opens the checkout page, because STRIPE_SECRET_KEY was never set.
Good: the server refuses to start, logs exactly which variables are missing, and the deploy fails immediately where someone is watching.
Zod is a natural fit if the project already uses it, and this blog’s Astro content pipeline uses the same pattern for frontmatter:
import { z } from 'zod';
const schema = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']),
PORT: z.coerce.number().int().positive().default(3000),
DATABASE_URL: z.string().url(),
DEBUG: z.coerce.boolean().default(false),
});
const parsed = schema.safeParse(process.env);
if (!parsed.success) {
console.error('Invalid environment configuration:');
console.error(parsed.error.flatten().fieldErrors);
process.exit(1);
}
export const env = parsed.data; // typed, validated, safe to import anywhere
Now env.PORT is a number, env.DATABASE_URL is guaranteed present, and a misconfigured deploy fails at 9 a.m. instead of silently at 3 p.m. This is exactly the “fail loudly and early” principle that makes systems that survive bad days possible, and the same validation instinct that keeps form validation patterns honest on the client.
The security reality of environment variables
Environment variables are the standard answer to “where do secrets go,” and for many deployments that is the right answer. But it is worth knowing the limits, because the framing “environment variables are secure” is not accurate.
Any process running as the same user can read them. On Linux, /proc/<pid>/environ is readable by the owning user. If your app has any code execution vulnerability, the attacker gets every secret it holds.
Child processes inherit everything. Shell out to ffmpeg, and it has your database password. Pass an explicit, minimal environment to subprocesses rather than inheriting the full set.
They leak into unexpected places. Crash reporters, error-tracking SDKs that capture request context, /debug endpoints, health checks that dump config, and container inspection tools all routinely surface environment values.
They appear in logs if anyone logs the environment. One console.log(process.env) in a debugging session, deployed, leaks everything.
Rotating them requires a restart. Unlike a secret fetched from a manager at runtime, an environment variable is a fixed snapshot — changing it means restarting the process.
The pragmatic hierarchy, from worst to best:
- Secret committed to git — never acceptable. Assume compromise.
- Secret in a
.envfile on a server — workable for a hobby deployment, fragile at any scale. - Secret in the platform’s encrypted secret store, injected as an environment variable — the normal, accepted production answer.
- Secret fetched at runtime from a dedicated secret manager (Vault, AWS Secrets Manager, Doppler), with short-lived credentials — the answer for anything sensitive and long-lived.
Most projects belong at level 3 and should know why level 4 exists.
Naming and documentation
Two conventions worth adopting without debate:
Uppercase with underscores. DATABASE_URL, not databaseUrl. It is the convention everywhere, and it keeps your application variables visually distinct from lowercase shell variables.
Prefix by scope when a project has many. AWS_, STRIPE_, NEXT_PUBLIC_ are all doing this. The prefix convention also has security meaning in some frameworks: in Next.js and Vite, only variables with a specific public prefix are exposed to browser bundles. Anything without that prefix is server-only — and leaking a server secret into a client bundle by adding the wrong prefix is a real and common breach.
Document every variable in .env.example with a one-line comment on what it is and where to get it. It costs nothing and saves every future contributor a Slack message.
A checklist to apply today
- Confirm
.envis in.gitignore— and check git history for one that was committed before. - Add
.env.examplewith every key, no values, one comment each. - Add a startup validation schema so missing config fails the boot, not the feature.
- Replace truthiness checks on environment variables with explicit string comparisons.
- Stop loading
.envin production; source config from the platform’s secret store. - Audit any public/prefix-exposed variable to make sure nothing sensitive is in it.
- Pass a minimal explicit environment to subprocesses instead of inheriting everything.
None of these take more than a few minutes, and each one removes a category of incident rather than a single instance of one.
The underlying principle is small and durable: the environment is where a deployment’s identity lives, and the code should be identical everywhere else. Once that separation holds, moving between local, staging, and production stops being a series of surprises.