简体   繁体   中英

Strategies for handling NodeJS environment specific configuration (Secret keys etc)

We are currently using 'nconf' npm module in nodejs to handle environment specific configuration using a single json configuration file. This configuration is then checked into a git repository and used by application. However, as the application grows we find that the configuration file now has confidential credential information. I wanted to find out what is a good way to handle these credential configuration per environment. I read in many forums that provide these credentials as environment run time parameter while starting Node server and not store them in source repositories. This is good, if you are manually starting the server, but we are planning on having dockerized automated container deployment. In that case we have to store the credentials configurations somewhere, so looking for suggestions on what would be a good strategy to deal with this situation.

I think it depend of the infrastructure that your using. For example if you use heroku you could set ENV_VARS there and thats it. Same if you own a server as an administrator you could set up those variables and you only know who has access to that.

I have done something similar with Heroku and the .env node library.

This library pushes a set of environment variables when the server starts from a .env file if found.

Create a .env file only in the local environment and set it in your .gitignore file so it won't get uploaded to your remote.

your .env file looks like this:

AMAZON_CLIENT_ID=ABCDEFG
AMAZON_CLIENT_SECRET=CATDOGCOW

I like to put all my configuration variables or constants into a single file so I can find them instead of widespread around the code.

So I make a file called config.js that looks like this

require('dotenv').config({silent: true});

module.exports = {
    AMAZON_CLIENT_ID:process.env.AMAZON_CLIENT_ID,
    AMAZON_CLIENT_SECRET:process.env.AMAZON_CLIENT_SECRET,
}

At least in Heroku, I can setup manually all those environment variables on the Heroku website and I would assume you can do something similar in Docker.

Then you use it anywhere in your code like:

var config = require('./config');
//some random code

if(req.query.amzclientid == config.AMAZON_CLIENT_ID)

I know it is not Docker, but if you are interested in knowing more of the above, I wrote a tutorial about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM