Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 263
Jonas Avatar asked Mar 28 '19 20:03

Jonas


People also ask

Can you have multiple .env files?

One solution is to have multiple . env files which each represent different environments. In practice this means you create a file for each of your environments: .

What is Node_env used for?

NODE_ENV is an environment variable that stands for node environment in express server. The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production).


2 Answers

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}` }) 
like image 100
Marlorn Avatar answered Oct 06 '22 18:10

Marlorn


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.

like image 32
Martin Omander Avatar answered Oct 06 '22 19:10

Martin Omander