Bun Environment Variables
Bun provides powerful environment variable management, automatically loading .env files, and offering multiple access methods. This chapter introduces Bun environment variables usage.
Auto-loading .env Files
Basic Usage
Bun automatically loads .env files in the project root:
Run:
Loading Order
Bun loads environment variables in the following order (later values override earlier ones):
- System environment variables
.envfile.env.localfile.env.development/.env.production(based on NODE_ENV).env.development.local/.env.production.local
Accessing Environment Variables
Using Bun.env
Using process.env
Type-safe Access
Multi-environment Configuration
Environment Files
.gitignore Configuration
Specifying Environment Files
Environment Variable Syntax
Basic Syntax
Variable References
Comments
Escape Characters
Configuration Validation
Startup Validation
Using Zod Validation
Dynamically Setting Environment Variables
Setting in Code
Subprocess Environment Variables
Security Best Practices
Sensitive Information Handling
Environment Variable Template
Create .env.example as a template:
Secret Management
bunfig.toml Environment Configuration
Special Environment Variables
Bun-specific Variables
Node.js Compatible Variables
Practical Examples
Complete Configuration Management
Using Configuration
Summary
This chapter covered:
- ✅ Auto-loading .env files
- ✅ Multiple ways to access environment variables
- ✅ Multi-environment configuration management
- ✅ Environment variable syntax and variable references
- ✅ Configuration validation and type safety
- ✅ Security best practices
Next Steps
Continue reading File I/O to learn about Bun's high-performance file handling capabilities.