Environment Variables: Best Practices and Pitfalls
Environment variables configure an application without changing code. Learn the patterns, the security rules, and the traps.
By Velloreth
What they are for
Environment variables configure an application without changing code. The same build runs in development, staging, and production, with different values.
The rule of thumb: values that differ per environment go in environment variables. Structured settings that are the same everywhere go in a config file.
They are strings
Every environment variable is a string. This is the source of many bugs.
// Bug: "false" is a truthy string
const debug = process.env.DEBUG;
if (debug) { /* always runs, even when DEBUG=false */ }
// Correct
const debug = process.env.DEBUG === 'true';
// Bug: string concatenation
const port = process.env.PORT + 1; // "30001"
// Correct
const port = Number(process.env.PORT) + 1;
Always parse explicitly, and validate the result.
Validation at startup
Fail fast rather than discovering a missing variable at runtime.
function required(name) {
const value = process.env[name];
if (!value) {
throw new Error(`Missing required environment variable: ${name}`);
}
return value;
}
const config = {
databaseUrl: required('DATABASE_URL'),
port: Number(process.env.PORT ?? 3000),
debug: process.env.DEBUG === 'true',
};
A schema validator makes this cleaner.
import { z } from 'zod';
const schema = z.object({
DATABASE_URL: z.string().url(),
PORT: z.coerce.number().default(3000),
DEBUG: z.coerce.boolean().default(false),
});
const config = schema.parse(process.env);
The application refuses to start with a bad configuration, which is far better than failing on the first request.
Naming
Prefix with the application name to avoid collisions.
MYAPP_DATABASE_URL
MYAPP_REDIS_URL
MYAPP_LOG_LEVEL
In a shared environment, an unprefixed PORT or URL can collide with another application.
Use SCREAMING_SNAKE_CASE. It is the convention and it distinguishes environment variables from local variables.
Be specific. DB_HOST is clearer than HOST, which could mean anything.
The .env file
A .env file holds values for local development.
DATABASE_URL=postgres://localhost:5432/app
PORT=3000
DEBUG=true
Never commit it. Add .env to .gitignore.
Commit a .env.example with the same keys and placeholder values.
DATABASE_URL=postgres://localhost:5432/app
PORT=3000
DEBUG=false
A new developer copies it and fills in the real values. This documents what the application needs.
Loading it. In Node, use dotenv or the built-in --env-file flag.
node --env-file=.env server.js
import 'dotenv/config';
Do not load .env in production. The platform provides the variables, and a stray .env file can override them.
Security
Environment variables are better than committing secrets, but they are not private.
They are visible to child processes. A subprocess inherits the environment, so a compromised dependency can read every secret.
They appear in /proc. On Linux, /proc/<pid>/environ contains the environment, readable by the same user.
They leak into crash reports. A stack trace or an error report may include the environment.
They appear in some debug endpoints. A /debug route that dumps the config is a common mistake.
For high-value secrets, use a secrets manager. Vault, AWS Secrets Manager, or a platform secret store fetches the value at runtime and can rotate it.
Never log the environment. A console.log(process.env) in production writes every secret to the logs.
Per-environment configuration
# development
DATABASE_URL=postgres://localhost:5432/app
LOG_LEVEL=debug
# production
DATABASE_URL=postgres://prod-host:5432/app
LOG_LEVEL=info
The same code reads the same variable names, and the values differ. This is the point: no code change between environments.
Do not branch on the environment name in application code.
// Fragile: behaviour depends on a string
if (process.env.NODE_ENV === 'production') { ... }
// Better: configure the behaviour directly
if (config.cacheEnabled) { ... }
The second version makes the behaviour explicit and testable, rather than inferring it from an environment name.
Setting them
For one command:
NODE_ENV=production node server.js
For the session:
export NODE_ENV=production
In a shell script:
export DATABASE_URL="postgres://..."
In Docker:
docker run -e NODE_ENV=production myapp
docker run --env-file .env myapp
In Compose:
environment:
NODE_ENV: production
env_file:
- .env
In CI:
env:
NODE_ENV: test
Common pitfalls
A variable set in one shell is not in another. Each shell session has its own environment.
export is needed for child processes. Without it, the variable is a shell variable, not an environment variable.
VAR=value # shell variable, not inherited
export VAR=value # environment variable, inherited
A .env file with quotes. Some loaders strip quotes, some do not. KEY="value" may include the quotes.
A trailing newline. A value read from a file may include a newline, which breaks a comparison.
Case sensitivity. PORT and port are different variables on Linux.
A variable name with a dash. MY-VAR is not a valid shell identifier. Use an underscore.
Testing with configuration
Configuration is a dependency, and tests should not depend on the developer’s environment.
Set the variables in the test setup, so a test does not pass because of a stray value in the shell.
beforeAll(() => {
process.env.DATABASE_URL = 'postgres://localhost:5432/test';
process.env.LOG_LEVEL = 'silent';
});
Inject configuration rather than reading it globally. A function that takes its configuration is easier to test than one that reads process.env directly.
// Hard to test: reads the environment
function connect() {
return pool(process.env.DATABASE_URL);
}
// Easy to test: takes the value
function connect(databaseUrl) {
return pool(databaseUrl);
}
Use a separate test environment file. A .env.test with safe defaults keeps the tests independent of the developer’s .env.
Never point a test at production. A test that writes to a real database is a data-loss incident waiting to happen. Use a local or ephemeral database.
Migrating configuration
Configuration changes over time, and a rename is a breaking change.
Support both names during a transition. Read the new name, fall back to the old one, and log a deprecation warning.
const databaseUrl = process.env.MYAPP_DATABASE_URL
?? process.env.DATABASE_URL;
if (!process.env.MYAPP_DATABASE_URL && process.env.DATABASE_URL) {
console.warn('DATABASE_URL is deprecated; use MYAPP_DATABASE_URL');
}
Update the .env.example so new developers use the new name.
Remove the fallback once every environment has been updated, and note the removal in the changelog.
Documentation
Configuration is an interface, and an undocumented interface is a support burden.
Keep .env.example current. Every variable the application reads should appear there with a placeholder and, ideally, a comment.
# Database connection string (required)
DATABASE_URL=postgres://localhost:5432/app
# HTTP port (default: 3000)
PORT=3000
# Enable verbose logging (default: false)
DEBUG=false
Document the type and the default. A reader should not have to read the code to know whether DEBUG is a boolean or a string.
Document which variables are required. A missing required variable should fail at startup with a clear message, and the documentation should say which ones those are.
Keep the documentation next to the code. A README section or a comment in the config module is more likely to stay current than a wiki page.
Practical guidance
- Parse explicitly — everything is a string.
- Validate at startup and fail fast.
- Prefix with the application name.
- Never commit
.env— commit.env.example. - Do not log the environment.
- Use a secrets manager for high-value credentials.
- Do not branch on
NODE_ENVin application code. - Use
exportfor child processes.
For the related guides, see environment-variables-explained and docker-basics-guide. For the broader context, twelve-factor-app-explained and encryption-at-rest-vs-transit.
Quotable summary
Environment variables are strings, so a boolean or a number must be parsed explicitly, and the string “false” is truthy in JavaScript. Never commit a .env file with real secrets; commit a .env.example with placeholders instead, so a new developer knows what to set. Validate configuration at startup and fail fast, rather than discovering a missing variable at runtime, and prefix variables with the application name to avoid collisions in a shared environment. Environment variables are visible to child processes, in /proc, and in some crash reports, so treat them as semi-public and use a secrets manager for high-value credentials. Never log the environment, because that writes every secret to the logs.