Best way to store DB config in Node.Js / Express app

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:

  1. 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?

  2. 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 :)


Solution 1:

Here's how I do it:

Create a config.js which contains objects representing your configs:

var config = {
development: {
    //url to be used in link generation
    url: 'http://my.site.com',
    //mongodb connection settings
    database: {
        host:   '127.0.0.1',
        port:   '27017',
        db:     'site_dev'
    },
    //server details
    server: {
        host: '127.0.0.1',
        port: '3422'
    }
},
production: {
    //url to be used in link generation
    url: 'http://my.site.com',
    //mongodb connection settings
    database: {
        host: '127.0.0.1',
        port: '27017',
        db:     'site'
    },
    //server details
    server: {
        host:   '127.0.0.1',
        port:   '3421'
    }
}
};
module.exports = config;

Then in my index.js (or wherever really),

var env = process.env.NODE_ENV || 'development';
var config = require('./config')[env];

Then process with that object, e.g.

var server = express();
server.listen(config.server.port);
...

Solution 2:

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 in process.env that you can refer to.

.env file:

DATABASE_PASSWORD=mypw
DATABASE_NAME=some_db

To refer to the values:

process.env.DATABASE_PASSWORD