How I Setup Environment Variables in NodeJS. No, it’s not “dotenv”

It’s very easy to set up environment variables in NodeJS using dotenv package. It works great, however as the app grows and there are more people working in the same team, we ran into some issues.

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 .env before 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

  1. Install ‘localenv‘ – npm i localenv
  2. Require it above all – require('localenv')
  3. Create .env file and add all your environment variables
  4. Override the variables by creating .env.local file
  5. Add .env.local to .gitignore
0 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like