Reputation: 1999
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?
Upvotes: 38
Views: 55808
Reputation: 15113
Yes, you can use multiple .env files without any hacks:
require('dotenv').config({
path: ['.env.local', '.env']
})
Be sure to update if you're using an older dotenv package. Your env vars will be set in left to right precedence (.env.local
vars win in the example above).
NOTE:
Multiple .env files is not a bad practice as stated in other answers (and old dotenv docs). There are numerous valid use cases for this. The bad practice is rather committing any .env files. This is now reflected in latest dotenv docs:
We strongly recommend against committing your .env file to version control.
Upvotes: 11
Reputation: 2474
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.
Edit - 2024 March
My above answer might be obsolete now since the package dotenv supports multiple env files for multiple envs via dotenvx - another package from the same creator that claims to be a better dotenv than dotenv.
https://github.com/dotenvx/dotenvx
Upvotes: 41
Reputation: 745
If .env.local
file present dotenv
will override .env
dotenv.config();
dotenv.config({ path: `.env.local`, override: true });
Upvotes: 22