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);

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


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

From dotenv documentation

Answered By – Matt

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published