Environment variables configure applications across environments. Here's how to use them effectively.
Basic Usage#
Using dotenv#
Configuration Module#
TypeScript Configuration#
Environment-Specific Files#
# File structure
project/
├── .env # Default/development
├── .env.local # Local overrides (gitignored)
├── .env.development # Development specific
├── .env.production # Production specific
├── .env.test # Test specific
└── .env.example # Template (committed)
Secrets Management#
Docker Configuration#
Testing with Environment Variables#
Validation and Defaults#
Best Practices#
Security:
✓ Never commit .env files
✓ Use .env.example as template
✓ Rotate secrets regularly
✓ Use secret managers in production
Organization:
✓ Group related variables
✓ Use consistent naming (UPPER_SNAKE_CASE)
✓ Document all variables
✓ Provide sensible defaults
Validation:
✓ Validate on startup
✓ Fail fast on missing required vars
✓ Type-check values
✓ Use schema validation (zod)
Development:
✓ Use dotenv for local dev
✓ Keep .env.example updated
✓ Test configuration loading
✓ Mock env vars in tests
Conclusion#
Environment variables are essential for configuration management. Use dotenv for local development, validate configuration on startup, and never commit secrets. Implement a robust configuration module with type safety and validation for production applications.