If you’ve ever needed to easily switch between different
.env files during local development this might be helpful. Recently I needed to find a way to switch between different environment files,
.env, to change the location/values I was using for local commands. More specifically I needed to switch my environment configuration from pointing to a local database to point to a staging database I have running in Google Cloud Platform(GCP) instead. I needed to switch my configuration to be able to perform a database migration. This is still a manual step (on purpose) to give a little more predictability about when and how the migration is performed.
Until recently I have been toggling between environments by commenting out one line of configuration for another. This back and forth was _ok_ for the very short-term, but we quickly ran into issues where we thought we were pointing to a local database when in fact we were pointing to a staging database being used by other folks on the team, no bueno!
I needed a solution that would allow me to continue using a local
.env file but substitute out certain values when toggling between environments. Also, making it required that I would have to be explicit if I wanted to run a command from my local machine on hosted resources, like a cloud database. A classic foot gun scenario.
The solution was to leverage an environment file package called dotenv-cli along with a few different
.env files, each specific for an environment.
.env file would be setup for local development, this is the file that all of my application code references by default. Each subsequent file would be named for the specific environment or purpose, e.g.
.env.demo. By using a tool like dotenv-cli I can augment or override specific values, i.e.
npx dotenv-cli -e .env.demo -e .env <Command to run>
This will combine both
.env files, however it requires us to be intentional as to how and when we run a command, like DB migration, on a give environment.