24

This might look like a newbie question, but I am unable to find the way to load environment variables from both .env and .env.local files in node with dotenv.

Is it even possible? How do people load environment variables from both files nowadays if not with dotenv?

Adrian
  • 1,558
  • 1
  • 13
  • 31

3 Answers3

31

Quoting from dotenv's npm page

Should I have multiple .env files?

No. We strongly recommend against having a "main" .env file and an "environment" .env file like .env.test. Your config should vary between deploys, and you should not be sharing values between environments.'

But to use .env.local or .env.test or any other environment.. one at a time is

require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` })

If you still want to do it refer to dotenv-flow at https://www.npmjs.com/package/dotenv-flow

dotenv-flow comes with the feature of overwriting variables at environments.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Venkatesh A
  • 1,875
  • 1
  • 19
  • 23
  • 2
    Just a small doubt. If we are using the process.env object to refer to the node env, are we setting the node env at the point where the script/app is being invoked at OS level? I have always used the .env file to set the NODE_ENV value as I have apprehensions that the OS level env variable might cause issues when multiple apps are used on the same instance – Naveen Venkatesh Apr 18 '22 at 06:50
  • Nope it loads variables from a .env file into the Node app on startup – Venkatesh A Apr 18 '22 at 16:02
  • 1
    Thanks. https://www.npmjs.com/package/dotenv-flow looks helpful. – Ryan Apr 29 '22 at 18:01
  • 1
    It's frustrating that this is at odds with the way create-next-app and next.js in general are set up to function by default which is to only look at a .env.local file. Feels like every time someone tries to confidently set down a rule in tech someone is already breaking it – ChrisM Mar 23 '23 at 09:07
13

If .env.local file present dotenv will override .env

dotenv.config();
dotenv.config({ path: `.env.local`, override: true });
mat.twg
  • 438
  • 1
  • 5
  • 11
2
dotenv.config({ path: '.env.local' });
dotenv.config();
Abdalla Roda
  • 607
  • 1
  • 6
  • 13