A foundational principle of well-built software is that the same code should run unchanged across different environments — your laptop, a test system, production — with only its configuration differing. Environment variables are the standard mechanism for achieving this, and using them well is a mark of maturity that also avoids some serious security mistakes.
The core idea is to separate what the program does from where and how it is running.
Why config doesn’t belong in code
Things like which database to connect to, which external service URL to use, and secret keys naturally differ between environments. Hard-coding them means editing source to move between environments, which is error-prone and dangerous. Worse, committing secrets directly into code is a common and costly security failure, since anyone with access to the repository then has the keys.
Configuration is not logic; treating it as data supplied from outside keeps the code portable and the secrets out of your history.
How environment variables help
Environment variables let the surrounding system provide configuration to the program at run time, so the same code reads different values in different places. Development points at development resources, production at production ones, and neither requires changing the code. Secrets can be injected by the environment rather than living in the source.
This cleanly realises the "same code, different config" ideal, and it is why the approach is so widely adopted.
Handling secrets carefully
A crucial caution: environment variables often hold sensitive values, so they must be managed with care. Keep files that contain real secrets out of version control, avoid printing them into logs, and use proper secret-management for production rather than scattering keys around. The goal is that a leak of your code never leaks your credentials.
Done right, environment variables give you portable code, clean separation of concerns, and a defensible place for secrets — a small practice with outsized benefits.