Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment variables(.env) in node js express

Is it possible to have a single .env file for all different deployment environments such as development, production , etc.Based on the environment the corresponding environment variables file needs to be loaded.

like image 477
goutham Avatar asked Feb 04 '18 06:02

goutham


2 Answers

Yes. You can use the dotenv module for example:

.env

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

app.js

require('dotenv').config()

const db = require('db')
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
}
like image 95
JazzBrotha Avatar answered Oct 11 '22 16:10

JazzBrotha


Yes, not necessarily .env file but a json/js file.

You can make a file like below and require this file with environment -

let config = require('./pathToFile/')[process.env.NODE_ENV]

Your file -

{
"development" : {
    "dbConfig" : {
        "username" : "acaca",
        "password" : "ajbcjdca",
        "port" : "acdc",
         "etc" : "etc"
    },
    "serverConfig" : {
      "host" : "jabcjac.com",
      "port" : "4545",
      "etc" : "etc"
    },
    "AWSConfig" : {
      "accessKey" : "akcakcbk",
      "etc" : "etc"
    }
},
"production" : {
    "dbConfig" : {
        "username" : "acaca",
        "password" : "ajbcjdca",
        "port" : "acdc",
         "etc" : "etc"
    },
    "serverConfig" : {
        "host" : "jabcjac.com",
        "port" : "4545",
        "etc" : "etc"
    },
    "AWSConfig" : {
        "accessKey" : "akcakcbk",
        "etc" : "etc"
    }
},
"test" : {
    "dbConfig" : {
      "username" : "acaca",
      "password" : "ajbcjdca",
      "port" : "acdc",
       "etc" : "etc"
    },
    "serverConfig" : {
      "host" : "jabcjac.com",
      "port" : "4545",
      "etc" : "etc"
    },
    "AWSConfig" : {
      "accessKey" : "akcakcbk",
      "etc" : "etc"
    }
}
}
like image 42
Rahul Avatar answered Oct 11 '22 17:10

Rahul