Managing environment variables in projects

Tucking away environment variables within the code can lead to maintenance headaches

Far too often in software projects, I come across the following:

if (process.env.RUN_SOMETHING) {

There is innately nothing wrong with this piece of code, it could be in file something.js on line 467, or in anotherThing.js on line 249. On its own, there simply is no fault to be found with this means of implementation. But when a project scales, this seemingly simple code pattern can lead to maintenance headaches; with the messy, decentralized and likely undocumented use of environment variables, which when used can have great impacts on the behavior of the application.

Profound picture to underline the importance of managing environment variables

Rather than referencing environment variables within the code, we should aim to centralize the use of environment variables, creating a self-documenting source of truth for all the environment variables within the application. The obvious location for this information is the config directory alongside all the other application settings. Here we could set defaults, separate the initialization by the environment, cast the environment variable into the expected type and make it easier to test different conditions without adjusting the environment variable.

Thus within our code, we could simply reference the config.

However, as with most other best practices in programming, the requisite for this format of code organization is vigilance. But with effort to code quality and maintenance, we can reduce this overhead and make a simpler time of it for developers to grasp the environment-specified capabilities of the application without digging into the codebase.