105

I want to use separate .env files for each mode (development, production, etc...). When working on my vue.js projects, I can use files like .env.development or .env.production to get different values for the same env key. (example: in .env.development: FOO=BAR and in .env.production: FOO=BAZ, in development mode process.env.FOO would be BAR, in production i'd be BAZ).

I'm working on an Express server and want to use these same kinds of .env files to store the port, db uri, user, pwd...

I know I can edit the scripts in package.json like this:

"scripts": {
    "start": "NODE_ENV=development PORT=80 node ./bin/www",
    "start-prod": "NODE_ENV=production PORT=81 node ./bin/www"
}

but this gets messy when using multiple variables.

I've tried using dotenv but it seems like you can only use the .env file. Not .env.development and .env.production.

Can I use the dotenv package or do I need another one? Or could I do this without any package at all?

3

8 Answers 8

171
+250

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}` })
6
  • 26
    For anyone else: i finally went with this: const path = require('path'); require('dotenv').config({ path: path.join(__dirname, ../.env.${process.env.NODE_ENV})});
    – Jonas
    Mar 30, 2019 at 9:41
  • If I use this solution I seem to need to place this line of code in every javascript file that I want to use the env values... Is there no global way so I can just have one line and all files access the values?
    – goldenmaza
    Dec 19, 2020 at 19:30
  • 8
    @goldenmaza You can preload them when running your node service in terminal like this. node -r dotenv/config app.js dotenv_config_path=/custom/path/to/your/env/vars. See also here npmjs.com/package/dotenv
    – Zwe
    Dec 28, 2020 at 23:45
  • 6
    NODE_ENV should not be used to set the application environment. A separate environment variable like APP_ENV may be used for this. You may want NODE_ENV to be production in your non production environments as well. nodejs.dev/learn/… Aug 30, 2021 at 8:16
  • 1
    @goldenmaza You shouldn't need to place this in every JS file. You'll want to add this as early as possible to your application bootstrap/entry point . Once it's added, you can access environment variables via process.env. Dec 3, 2021 at 18:39
11

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}`)
1
  • 2
    if you dont have a NODE_ENV this will give .env.undefined
    – dcsan
    Aug 14, 2022 at 19:07
6

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.

0
3

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}`)});
0
3

For Typescript:

import dotenv from 'dotenv'
dotenv.config({ path: `.env.${process.env.NODE_ENV}` })
0

Install the dotenv package:

npm install dotenv

We need to get the .env file name based on NODE_ENV, it might be undefined, set default to development:

const envFileName = `.env.${process.env.NODE_ENV || "development"}`

Import the dotenv package and use it:

dotenv.config({ path: envFileName });
0

This work for me:

File .env

NODE_ENV=dev
DB_HOST=localhost

File .env.dev

DB_HOST=dev-host
DEV_VAR=new-variable

Code

require("dotenv").config();

if (process.env.NODE_ENV === "dev") {
  const result = require("dotenv").config({ path: ".env.dev" });

  process.env = {
    ...process.env,
    ...result.parsed,
  };
}

const dbConfig = {
  host: process.env.DB_HOST,
};

console.log(dbConfig.host);
console.log(process.env.DEV_VAR);
-5

The official doc of dotenv does not recommend having multiple .env files.

"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."

10
  • 9
    DV bc This misinterprets either OP question or the doc: the doc advice is against using multiple .env files in the same environment (eg, loading main.env and test.env in the same process), not blanket advice against having multiple files.
    – FrozenKiwi
    Mar 18, 2021 at 11:04
  • 2
    Apologies for DV @rom5jp (I would remove it if I could). I re-read the docs, and it does sound like it doesn't recommend multiple files. However, I suspect this advice was not intended for this context, as it basically negates most of the utility of .env file in the first place (unless you never run multiple environments on your local machine).
    – FrozenKiwi
    Mar 19, 2021 at 15:19
  • 5
    In my opinion, the quoted recommendation against multiple .env files is poorly written and it's not clear what they mean. I agree that your config should vary between environments. But that means you will need one env file per environment. I think @FrozenKiwi is right: the recommendation is probably against multiple env files for one particular environment. Jun 4, 2021 at 21:14
  • 1
    I think we've all been confused by the dotenv's wording. They say 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., which seems like it discourages overrides/combinations -- the "AND" is the operative word. I think he majority of us are more curious about different local environments (e.g., .env.development, .env.production, etc) to test code locally w/ different resources.
    – Mike
    Apr 23, 2022 at 18:43
  • 1
    I also want to highlight their expectations/advice in how the .env is intended to be used. They say It should only include environment-specific values such as database passwords or API keys, which might explain why they don't expect to use a combination of environment files. Per: github.com/motdotla/dotenv#should-i-commit-my-env-file
    – Mike
    Apr 23, 2022 at 18:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.