Decoupling Config

Sometimes apps batch config into named groups (often called “environments”) named after specific deploys, such as the development, test, and production environments in Rails. This method does not scale cleanly: as more deploys of the app are created, new environment names are necessary, such as staging or qa. As the project grows further, developers may add their own special environments like joes-staging, resulting in a combinatorial explosion of config which makes managing deploys of the app very brittle.

This is something I’ve come across and been guilty of in the past, a specific config setup doesn’t quite match what you need so you amend it and create a new one called something like staging-qa. By doing this you’re polluting your codebase and making maintenance more onerous.

The alternative is to not group any config and treat each environment variable as a completely separate value. For example, you need authentication and a username and password adding to your qa and staging environments to ensure only specific people can view your application. Here’s how that could look with environment variables;

SECURED=true USERNAME=user PASSWORD=pass npm start

You can now check process.env.SECURED in your code to see if you need to do an authentication check and can then use the values of process.env.USERNAME and process.env.PASSWORD to validate users against.

If you decide to open up your staging environment then a fresh deploy with SECURED set to false is all that’s needed.

It’s worth noting that environment variables are always converted to strings so be careful when evaluating whether a value is true or false. You can work around this for variables you want to be boolean with code similar to below.

const SECURED = process.env.SECURED === `true`

In production you may not need any authentication which means these environment variables don’t need to be set, you can run npm start. Because process.env.SECURED will evaluate to false the check will not happen and the other two environment variables will not be checked.