Environment Variables
.env files, process.env, secrets, and configuration management.
Configuration does not belong in code
Your app needs different settings in different places: a local database on your laptop, a production database in the cloud; verbose logging in development, quiet logging in production; and secrets — API keys, passwords — that must never be committed to git.
Environment variables solve this. They are key-value strings the operating system passes to a process at startup. The same code reads its configuration from the environment, so deploying to a new environment means changing variables, not code. This is the third rule of the well-known Twelve-Factor App methodology.
// process.env is an object of string values:
console.log("NODE_ENV:", process.env.NODE_ENV ?? "(not set)");
console.log("HOME:", process.env.HOME ?? process.env.USERPROFILE);
// A typical pattern - a default for local development:
const port = Number(process.env.PORT ?? 3000);
console.log("Would listen on port:", port);Everything is a string
The single biggest env-var gotcha: every value is a string. PORT=3000 gives you the string "3000". DEBUG=false gives you the string "false" — which is truthy in JavaScript!
- Numbers: convert with
Number(process.env.PORT) - Booleans: compare explicitly —
process.env.DEBUG === "true" - Missing variables are
undefined, so provide defaults with??
Parse and validate configuration once, at startup, and export a typed config object — don't sprinkle raw process.env reads through the codebase.
process.env.DEBUG = "false"; // set for demonstration
// WRONG - "false" is a non-empty string, hence truthy:
if (process.env.DEBUG) {
console.log("Oops - this runs even though DEBUG is 'false'!");
}
// RIGHT - compare explicitly:
const debug = process.env.DEBUG === "true";
console.log("debug enabled?", debug);
// Numbers need converting too:
process.env.PORT = "8080";
console.log(typeof process.env.PORT, "->", typeof Number(process.env.PORT));.env files
Exporting variables by hand every session is tedious, so development settings live in a .env file — plain KEY=value lines in the project root.
Since Node 20.6 you can load one natively with node --env-file=.env app.js — no package needed. (The dotenv npm package does the same for older versions.)
Two iron rules:
- Add .env to .gitignore. It holds secrets; it must never be committed.
- Commit a .env.example with the same keys and placeholder values, so teammates know what to configure.
# .env (never commit this file!)
NODE_ENV=development
PORT=3000
DATABASE_URL=postgres://localhost:5432/myapp_dev
API_KEY=sk-local-dev-key-here
LOG_LEVEL=debug
# Load it natively (Node 20.6+):
# node --env-file=.env server.jsNODE_ENV and a central config module
NODE_ENV is a convention the whole ecosystem understands: "development", "production", or "test". Libraries change behavior based on it — Express caches templates in production, error pages hide stack traces, and so on.
The cleanest pattern is one config module that reads, converts, validates, and freezes all configuration at startup. Everything else imports the config object — if a required variable is missing, the app fails immediately and loudly instead of crashing an hour later.
function required(name) {
const value = process.env[name];
if (value === undefined) {
throw new Error("Missing required env var: " + name);
}
return value;
}
process.env.DATABASE_URL = "postgres://demo"; // demo value
const config = Object.freeze({
env: process.env.NODE_ENV ?? "development",
port: Number(process.env.PORT ?? 3000),
databaseUrl: required("DATABASE_URL"),
isProduction: process.env.NODE_ENV === "production",
});
console.log(config);Secrets hygiene
Environment variables are the standard delivery mechanism for secrets, but they still demand care:
- Never commit .env files — and if a secret ever lands in git history, rotate it (change the key); deleting the file is not enough
- Never log
process.envwholesale — it will end up in log aggregators - In production, prefer your platform's secret store (AWS Secrets Manager, Vault, etc.), which injects values as env vars at deploy time
- Grant each service only the secrets it needs
A leaked API key is a breach, not an inconvenience — treat every secret as radioactive.
Check your understanding
5 questionsQuestion 1 of 5
Score: 0