14

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

leogoesger
  • 3,476
  • 5
  • 33
  • 71
  • 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 Nov 28 '17 at 05:15

3 Answers3

21

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.

Dan K.K.
  • 5,915
  • 2
  • 28
  • 34
9

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

Matt
  • 1,068
  • 6
  • 10
  • 20
    How can I load the .env in testing env then? –  coinhndp Jun 19 '19 at 07:12
  • 1
    For those trying to use items in .env file inside of jest, follow this. Make sure your path to your .env file is from the starting point of your test file. And you may have to restart your terminal for changes to take affect. https://stackoverflow.com/questions/61781150/jest-test-not-reading-environment-variables-with-dotenv – Kuda Dec 26 '20 at 21:48
1

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

Erisan Olasheni
  • 2,395
  • 17
  • 20