Environment Variables in Node.js: The Complete Guide (2026)
Environment Variables in Node.js: The Complete Guide (2026) Environment variables are the standard way to configure apps across environments. Here's how to use them correctly. What and Why What: Key-value pairs set outside your application code Where: OS environment, .env files, CI/CD config, container orchestration Why: → Separate config from code (12-Factor App methodology) → Same code runs everywhere (dev, staging, production) → Secrets never committed to git → Easy to change behavior without redeploying Reading Env Vars in Node.js // Method 1: process.env (built-in, always available) const port = process . env . PORT || 3000 ; const dbUrl = process . env . DATABASE_URL ; const apiKey = process . env . API_KEY ; // ⚠️ process.env values are ALWAYS strings! const timeout = parseInt ( process . env . TIMEOUT , 10 ) || 5000 ; const debug = process . env . DEBUG === ' true ' ; const maxRetries = Number ( process . env . MAX_RETRIES || ' 3 ' ); // Method 2: dotenv (most popular approach) // npm install dotenv import ' dotenv/config ' ; // Loads .env into process.env automatically // Now process.env has all your .env variables! // Or explicit load: import dotenv from ' dotenv ' ; dotenv . config ({ path : ' .env.local ' }); // Custom file path // Method 3: env-cmd (for package.json scripts) // "dev": "env-cmd -f .env.dev node server.js" // "prod": "env-cmd -f .env.prod node server.js" // Method 4: tenv / enve (type-safe alternatives) import { env } from ' tenv ' ; const port = env . number ( ' PORT ' , 3000 ); // Type-safe with default const dbUrl = env . string ( ' DATABASE_URL ' ); // Required, throws if missing const debug = env . bool ( ' DEBUG ' , false ); // Boolean parsing The .env File Ecosystem # .env (committed to git with defaults) NODE_ENV = development PORT = 3000 LOG_LEVEL = debug # .env.local (NOT committed! Gitignored) # Contains local overrides and secrets DATABASE_URL = postgresql://localhost/myapp_dev API_KEY = sk_test_local_key JWT_SECRET = local-de