leogoesger
leogoesger

Reputation: 3830

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

Upvotes: 15

Views: 28702

Answers (3)

Dan K.K.
Dan K.K.

Reputation: 6094

Please consider using dotenv-flow (an npm package).

dotenv-flow extends dotenv, adding support of NODE_ENV-specific .env* files like .env.development, .env.test, .env.stage, and .env.production, and the appropriate .env*.local overrides.

It allows your app to have multiple environments (like "development", "test", "stage", and "production" respectively) with selectively-adjusted environment variable setups and load them dynamically depending on the current NODE_ENV.

In addition to that, .env*.local overrides add the ability to overwrite variables locally for development, testing, and debugging purposes (note that the appropriate .env*.local entry should be added to your .gitignore).

So, as you can see, dotenv-flow has a slightly different approach to managing .env* files under version control. Please refer the Files under version control section to learn more.

Upvotes: 22

Erisan Olasheni
Erisan Olasheni

Reputation: 2905

custom-env also solves this problem, it allows multiple configurations file for different environments. npm install custom-env. You can also specify which .env file to use on the go. require('custom-env').env('test');.

Full Docs here: https://www.npmjs.com/package/custom-env

Upvotes: 1

Matt
Matt

Reputation: 1196

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

Upvotes: 8

Related Questions