Managing/ Externalizing configurations in NodeJS


With the help of module.exports feature you can move all the configurations into a separate file and you can import that into any file in your NodeJS application. Let say i have few configurations like port and MongoDB credentials that i want to put in a separate file named config.js Then the code looks like following.

config.js

var express = require('express');
var router = express.Router();

var config = {
  port : 5000,
  mongo : {
    production: 'mongodb://myuser:some_strong_password@localhost:27017/db_user',
    local: 'mongodb://myuser_with_no_password@localhost:27017/db_user',
  },
  someOtherConfig: {
    foo: 'bar',
    age: 24
  }
}

module.exports = config;

As you can see in the above code, you have created a file named config.js and exported the config. Now you can import this module in any file using require and can start using it. For example if you want to refer this config in index.js where you start your Node application and connect to MongoDB, your code looks like following

The way you access in other files

var config = require('./config');
console.log('Port' + config.port);

More realistic examle usage

var express = require('express');
var app = express();

var MongoClient = require('mongodb').MongoClient;
var config = require('./config');

// Mongo Connection
db = {};
var mongoDbUri = config.mongo.local;
if(process && process.env && process.env.environment == 'production') {
   mongoDbUri = config.mongo.production;
}

var settings = {
      reconnectTries : Number.MAX_VALUE,
      autoReconnect : true
};

MongoClient.connect(mongoDbUri, settings, function(err, dbref) {
  if (!err) {
    console.log("Mongodb connected");
    db = dbref;
  }
});

// Start application
// Start App
app.set('port', (process.env.PORT || config.port));
app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

As shown in above example all you need to use the config is first import using require and then start using it.