What would be the best way to store DB config (username, password) in an open source app that runs on node.js / Express? Two specific questions:
Shall I put it into a separate config.js file in
/lib
folder, for example, and never include it into the master repository that is publicly available on GitHub?To inlcude the config, is it as simple as
require('./config.js')
from the file that needs it or is there a better way of doing it?
PS sorry if the questions seem a bit simple or not so well formulated, but I'm just starting :)
For running toy apps where I need to hide db credentials, I use the dotenv module.
Place your sensitive info in a .env file (which is .gitignored), place
require('dotenv').config();
in your app; dotenv creates entries inprocess.env
that you can refer to..env
file:To refer to the values:
I do put in args. just like the port of so many node.js example. you most likely forever, pm2, nodemon to run your app. so this variable is not check in as part of your source code. and they are globally available too.
Not sure whether this is the best practice, but personally I have a
config.json
file where I store my db connection information. Then I do the following:Then from a different file I do the following:
Here's how I do it:
Create a config.js which contains objects representing your configs:
Then in my index.js (or wherever really),
Then process with that object, e.g.
I found this a nice way to handle my config, considering different environments:
config.coffee
server.coffee:
This is the right way to store config files.
The best approach would be to write your entire application like an ordinary node.js module, and write a small start-up file that calls it. This idea also allow you to use different database drivers using dependency injection.
Good, but not perfect solution is the environment. It is shared among all application, so if you have certain data you want to be available to all of them, this is the best bet. But if you have a config for one particular app, not much so.
PS: And please, don't use JSON for this. It's the worst idea possible. :)