I have two dotenv files, one for development and another for test.
const dotenv = require('dotenv');
if (process.env && process.env.NODE_ENV) {
dotenv.config({path: '.env.' + process.env.NODE_ENV});
} else {
dotenv.config({path: '.env.development'});
}
const http = require('http');
const app = require('../src/app');
const port = parseInt(process.env.PORT, 10) || 8000;
app.set('port', port);
const server = http.createServer(app);
server.listen(port);
Here are my questions:
When does server load dotenv files in my case? If I run in test
env, why do I get undefined for those process.env variables?
It seems to me this file only runs once, when I change NODE_ENV, it does not change which file to load.
So in short:
My development dotenv is working, but just having trouble when changing it to test
dotenv
Preload. You can use the --require ( -r ) command line option to preload dotenv. By doing this, you do not need to require and load dotenv in your application code. This is the preferred approach when using import instead of require .
To use DotEnv, first install it using the command: npm i dotenv . Then in your app, require and configure the package like this: require('dotenv'). config() .
By default, it won't overwrite existing environment variables as dotenv assumes the deployment environment has more knowledge about configuration than the application does. To overwrite existing environment variables you can use Dotenv.
Please take a look at the dotenv-flow package.
This module extends dotenv adding the ability to have multiple .env*
files like .env.development
, .env.test
, .env.production
, etc., also allowing defined variables to be overwritten individually in the appropriate .env*.local
file that is untracked by VCS.
Regarding to the recommendation against having multiple env files, dotenv-flow has a slightly different approach to manage .env*
files under version control. Please refer the Files under version control section to understand the motivation of this approach.
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.
From dotenv documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With