goutham
goutham

Reputation: 323

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.

Upvotes: 32

Views: 69717

Answers (4)

mobentu
mobentu

Reputation: 31

yes too late for answer to this question..

but have a simple and easy way for use env file in express or any other node apps and no need install external package.

node --env-file=.env app.js

Also, you can pass multiple env file arguments. Subsequent files override pre-existing variables defined in previous files.

node --env-file=.env --env-file=.development.env app.js
  • you need nodejs +20
  • for more detail visit original nodejs document from here

Upvotes: 1

Mohit Sharma
Mohit Sharma

Reputation: 677

Install the dotenv module

npm install dotenv 

.env

NODE_ENV=development
PORT=3000

index.js

let dotenv = require('dotenv').config()
console.log(dotenv);

Output:-

{ parsed: { NODE_ENV: 'development', PORT: '3000' } }

File strictures:-

---| index.js
   | .env

Upvotes: 11

JazzBrotha
JazzBrotha

Reputation: 1748

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
}

Upvotes: 54

Rahul
Rahul

Reputation: 942

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

Upvotes: 0

Related Questions