12
votes

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

3
That should work. Perhaps it's how you run your setup. Perhaps ensure you are getting the correct path for console.log('.env.' + process.env.NODE_ENV) when running in test mode? - cyberwombat

3 Answers

19
votes

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.

5
votes

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

0
votes

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