How do you load environment variables from .env and .env.local with dotenv?

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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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.

Solution 2

dotenv.config({ path: '.env.local' });
dotenv.config();

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply