Toggle between multiple .env files like .env.development with node.js

I just wanted to add this for other people who are having issues. There is no need to get extra npm packages such as custom env. As a security researcher I suggest avoiding extra NPM modules especially ones that deal with your secrets/env variables.

The above two answers are both slightly off. let me explain. Answer from KyleMit below is missing ./ to indicate current directory.

  • the ./ indicates current directory in Node.js. The Second . prior to env indicates a hidden/private file. Thats why in KyleMits answer if the env file was not in the root of the PC it would never find it. The simplest way to do it in my opinion is to add a ./ this says "hey computer look in my current directory for this file".
//look in my current directory for this  hidden file. 
// List hidden files in dir: ls -a
 
require('dotenv').config({ path: `./.env.${process.env.NODE_ENV}` })


//I reccomend doing a console.log as well to make sure the names match*
console.log(`./.env.${process.env.NODE_ENV}`)

I'm using the custom-env npm package to handle multiple .env files. Just put this at the top of your code:

require('custom-env').env();

and it will load environment variables from the file .env.X, where X is the value of you NODE_ENV environment variable. For example: .env.test or .env.production.

Here is a nice tutorial on how to use the package.


From answers from above: This is the final result that worked for me.

.env.dev file in src dir.

import path from 'path';

dotenv.config({ path: path.join(__dirname, `./.env.${process.env.NODE_ENV}`)});

You can specify which .env file path to use via the path option with something like this:

require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` })