Changing or Combining Local .env Files

03-07-2022

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.

The main .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. DB_HOST.

The files:

.env

1
2
3
4
5
6
7
8
9
10
11
# POSTGRES
POSTGRES_USER=myuser
POSTGRES_PASSWORD=password
POSTGRES_DB=local_dev

DB_HOST=localhost
DB_PORT=5432
DB_SCHEMA=public

# Database Connection
DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${DB_HOST}:${DB_PORT}/${POSTGRES_DB}?schema=${DB_SCHEMA}

.env.demo

1
2
3
4
5
6
POSTGRES_USER=myuser
POSTGRES_PASSWORD=supersecretdbpassword
POSTGRES_DB=demo

DB_HOST=123.132.456
DB_PORT=5432

The Command:

1
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.

Inspired by DigitalOcean - How To Use Environment Files with env-cmd