It’s very easy to set up environment variables in NodeJS using dotenv package. It works great, however as the
I was a huge fan of dotenv until I started to work in a team!
What’s wrong with dotenv?
Dotenv suggests that you shouldn’t commit your .env file as per The Twelve-Factor App. I followed them as they said, but things didn’t go well in our team.
- Whenever we add a new env variable we need to inform our teammates about the new one, since it’s not committed
- Some variables like 3rd party tokens are specific to each developer. Those need to be changed in
.envbefore running. Often they forgot and commit them, which creates a big mess!
- Support different variables for different environments like Development, Staging, Production, etc
Setting Environment Variables in NodeJS – The Right Way!
We came to the conclusion that the
.env files should work something like this:
- ‘.env’ should be committed
- A way to override variables in ‘.env’ by ‘.env.local’ (which shouldn’t be committed)
- Env files specific to Environment like ‘.env.production’.
Luckily I found a package that can do this – localenv
How to Use ‘localenv’ Package
- Install ‘
npm i localenv
- Require it above all –
.envfile and add all your environment variables
- Override the variables by creating