What Are Environment Variables?
Some information shouldn't live in your code. Passwords, API keys, database addresses — these need to stay secret and often change between your laptop and a production server. Environment variables solve this by storing configuration outside your source files.
Think of environment variables like settings on your phone. They configure how apps behave without changing the apps themselves. Your code reads these values at runtime, adapting to wherever it's running.
What They Look Like
Environment variables are simple key-value pairs:
DATABASE_URL=postgres://localhost/myapp
API_KEY=sk-abc123secret
DEBUG=true
PORT=3000
Your program reads these values when it starts. The same code can connect to a test database on your laptop and a production database on a server — just by changing the environment variables.
Why Use Them?
Security: API keys and passwords stay out of your code. If someone sees your source files, they don't see your secrets.
Flexibility: Change configuration without changing code. Switch databases, enable features, adjust settings — all without editing a single line.
Environments: Development, staging, and production often need different settings. Environment variables make this seamless.
Collaboration: Each developer can have their own local settings without affecting others.
The .env File
Typing environment variables every time you run a program gets tedious. The .env file solves this — a simple text file in your project folder:
# .env file
DATABASE_URL=postgres://localhost/myapp
API_KEY=sk-abc123secret
DEBUG=true
Your application loads this file at startup. Tools like python-dotenv (Python) or dotenv (Node.js) handle this automatically.
Critical rule: Never commit .env files to Git. Add .env to your .gitignore file immediately. Accidentally pushing secrets to GitHub is a common and serious mistake.
Reading Environment Variables in Code
Here's a preview of how you'll access these values:
import os
api_key = os.environ.get("API_KEY")
const apiKey = process.env.API_KEY;
We'll use environment variables extensively in Track 4 when building real projects. For now, understand the concept: keep secrets safe, keep code flexible.