Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node dotenv files not loading for test env

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

like image 426
leogoesger Avatar asked Nov 27 '17 22:11

leogoesger


People also ask

How do you preload 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 .

How do I require a dotenv file in Node JS?

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() .

Does dotenv override environment variables?

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.


2 Answers

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.

like image 127
Dan K.K. Avatar answered Oct 06 '22 20:10

Dan K.K.


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

like image 27
Matt Avatar answered Oct 06 '22 20:10

Matt