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.
4 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
}
Comments
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
Comments
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"
}
}
}
2 Comments
goutham
Hi Rahul, Thanks. But the application requires .env file which has all the environment related configuration which is necessary for the application. The purpose of .env is it varies for each environment. We need to achieve this for .env so that deployment becomes easier and does not require to keep changing the content of file manually.
Nilpo
@goutham It's generally considered bad practice to use .env files in production. The production environment should always be set explicitly. An incorrectly configured web server can serve the .env file to the public. You also risk accidentally committing it to source control.
.envformat? Why can't you use a.jsonfile?.jsonextension to that. You can have a file calledenv.jsonand include all passwords etc there. You don't need to include the file in your repository.