Environment variables store configuration outside your code. Think of them as a settings file - change settings without changing code.
Like game settings (volume, difficulty) stored separately from the game code. Environment variables store API keys, database URLs, etc. outside your code - change environments without code changes!
Why Use Them?
- ๐ Security: Keep secrets out of code
- ๐ Flexibility: Different settings per environment
- ๐ฆ Portability: Same code, different configs
- ๐ฅ Team Collaboration: Each dev has own settings
Common Variables
- ๐ API_KEY: Third-party service keys
- ๐พ DATABASE_URL: Database connection
- ๐ PORT: Server port number
- ๐ท๏ธ NODE_ENV: development/production
- ๐ง EMAIL_SERVICE: Email provider settings
How to Use
// Access environment variable
const apiKey = process.env.API_KEY;
const dbUrl = process.env.DATABASE_URL;
.env File
API_KEY=your_secret_key_here
DATABASE_URL=postgres://localhost/mydb
PORT=3000
NODE_ENV=development
Best Practices
- ๐ซ Never Commit: Add .env to .gitignore
- ๐ Document: Provide .env.example
- ๐ Secrets: Use for sensitive data
- โ Validate: Check required variables exist
Environments
- ๐ป Development: Local machine
- ๐งช Testing: Test database
- ๐ญ Staging: Pre-production
- ๐ Production: Live site
The bottom line: Environment variables store configuration outside code. Like a settings file, they let you change behavior without changing code!