Environment variables and config
Some values can't be written into your code: keys, passwords, the address of a service. And some need to change depending on where the app runs. Code you test on your laptop (the dev environment) should talk to a test database; the live app your users touch (the prod, or production, environment) must talk to the real one — using the same code.
The answer is environment variables (often "env vars"): named values that live outside the code and get supplied to it when it runs. The code says "give me DATABASE_URL," and the environment decides which one to hand over.
# A config file (e.g. .env) — values live here, not in the code
DATABASE_URL=postgres://localhost/myapp_dev
STRIPE_SECRET_KEY=sk_test_51H... # dev = a test key
SEND_REAL_EMAILS=false # don't email real users while testing
Two rules will save you real pain:
- Secrets never go in the code. Anything in your code can end up public (especially in a shared repo), and a leaked payment key or database password is a genuine emergency. Secrets belong in env vars, kept out of version control.
- Dev and prod are different. The point is that the same code behaves correctly in both, because the environment — not the code — decides which database and keys to use.
Same code, two homes — the env vars are what differ:
SAME CODE
/ \
▼ ▼
┌─────────────────┐ ┌─────────────────┐
│ DEV │ │ PROD │
│ your laptop │ │ hosting (cloud)│
│ test database │ │ real database │
│ test API key │ │ live API key │
│ fake emails │ │ real emails │
└─────────────────┘ └─────────────────┘
only you see it your users see it