Where should I store secret strings on Node server?

后端 未结 4 1361
臣服心动
臣服心动 2021-02-05 12:29

Well, I\'ve come with a problem. How can I store passwords, db url and important strings that should not go to my public version control?

I\'ve come up with 3 solutions.

相关标签:
4条回答
  • 2021-02-05 12:38

    There's a node package that handles this very similar to the Ruby On Rails approach with their credential system: schluessel

    It lets you save your secrets in an encrypted vault file and stores the key separately. This vauft file can be checked into your version control system, as long as you keep your key file secret.

    You can create vault files for different NODE_ENVs. If you surrender the key either via a key file or via an environment variable, you can access your credentials very easily from within your app.

    0 讨论(0)
  • 2021-02-05 12:46

    The common solution is to add a config.js.example file to version control (that contains empty/dummy values to document what's available).

    Then you add config.js to .gitignore (or whatever suits your VCS).

    To run your application you simply copy config.js.example to config.js and put in the proper values.

    Of course the path to config.js can be taken from an environment variable to allow easily using different configs - but still, you wouldn't put the actual config files under version control (unless you have a separate private repo for config files etc)

    It does make sense to always require a config file to exist. Even in development. While the default settings may be suitable, chances are good that many developers on your application want to configure things anyway or simply test things with non-default values.

    0 讨论(0)
  • 2021-02-05 12:46

    Here is my suggestion:

    1. Using a mix of file and env variables

    You can manage secret strings using a mix with config files and process.env variables.

    You can do something like this:

    var port = process.env.PORT || config.serverPort;
    

    Since now, working with docker is the rule, you should try this one.

    2. Using a Sample

    You could add a config.json.example to your repo with an example of the variables you should define but here you will have to remember to change it when you deploy to production.

    Just remember to add the real config.json to the .gitignore file. This one is not my preferred but still an option.

    0 讨论(0)
  • 2021-02-05 12:48

    The dotenv package can be used to load configuration and secrets from a .env file into process.env. For production, the .env file doesn't have to exist.

    Example:

    require('dotenv').config();
    
    const oauth2 = require('simple-oauth2').create({
      client: {
        id: process.env.TWITTER_CONSUMER_KEY,
        secret: process.env.TWITTER_CONSUMER_SECRET
      }
    });
    

    .env file:

    TWITTER_CONSUMER_KEY=bMm...
    TWITTER_CONSUMER_SECRET=jQ39...
    

    .gitignore:

    .env
    
    0 讨论(0)
提交回复
热议问题