Environment Variables: Patterns and Gotchas
On this page
Why Configuration Matters
Hardcoded values are one of the fastest ways to break production systems. Environment variables allow the same codebase to run in development, staging, and production without modification.
Accessing Environment Variables
const port = Number(process.env.PORT ?? 3000);
console.log('Running on port:', port);
process.env Is Always String
All values in process.env are strings. You must manually convert them to numbers or booleans.
Validation Strategy
Never assume environment variables exist. Validate them at startup.
function requireEnv(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`Missing environment variable: ${name}`);
}
return value;
}
Configuration Layer Pattern
Create a dedicated config module that reads and validates environment variables once, then exports typed configuration values.
Secrets
Never commit secrets to version control. Use environment variables or secret managers in production systems.
Production Perspective
- Validate at startup.
- Fail fast if config is invalid.
- Separate config from business logic.