[MEAN] How to have separate config settings for different environments

OK we have a MEAN app that we want to deploy to AWS or Heroku i.e. in a different environment. This always means that we have to deal with multiple configuration settings. It can be a tedious game of snakes and ladders and we want to minimise the migraine (ha, not migration) and arm-wrangling.

The Twelve-Factor app methodology suggests that we store the config in the environment itself [ref: https://12factor.net/config] (ahem) so that (drumrolls ...) we do not have to have a multiplexer in our code to provide the config settings accordingly to the environment (clang!). Hurrah for less code ... blah.

Great! So how to go about it then? We can use dotenv for this purpose. It reads in a .env file and then export/load the settings to process.env (tata). Yes indeed, we will outsource this grand responsibility of maintaining the config settings to process.env.

npm install dotenv --save

On the very first line of your app.js

require('dotenv').config()

Create a .env file in your project root directory and add it to .gitignore. It has to be just .env and where you start your app.

//.env
?
DB_HOST=localhost
DB_USER=root
DB_PASS=verycomplicatedpassword
PORT=8080

Yes, this means that we have to login to the environment itself and create this file. It is just one additional (small) step (for the developer) but this is the so-called "storing the config in the environment" and therefore "not in code" since it is in .gitignore.

OK, we have to do a bit of code refactoring as well to get the config settings from the process.env object. For example,

const NODE_PORT = process.env.PORT || 3000


For heroku, we do not need to use dotenv at all but instead make use of the heroku config. We can set the config settings like in the following example

heroku config:set S3_KEY=8N029N81 S3_SECRET=9s83109d3+583493190

and then access them as process.env.S3_KEY and process.env.S3_SECRET respectively. You can refer to the following Heroku documentation (https://devcenter.heroku.com/articles/config-vars)

Hopefully this article has helped you as much as it did for me (it lit up a LED bulb in my case). Thanks for reading and do let me know if you have any questions.

William Ku

Cloud Software Engineer

6 年

Another way will be to use the npm config package. Will discuss about this in another article

回复

要查看或添加评论,请登录

William Ku的更多文章

社区洞察

其他会员也浏览了