Storing Node.js application config data

I’ve tried multiple approaches to storing application configuration with Node.js but most have been painful until I found this solution.

tl;dr: Executable configuration FTW via exports.

With Node.js you can export an object or function for use within another module. This is key to keeping your Node.js application readable and structured which as I’ve found can be an art-form in itself.

My current approach is as follows.

I have a config.js which looks like this.

var url = require(‘url’)

var config = {} = {};
config.redis = {}; = process.env.GOOGLE_ID || ‘’;  process.env.GOOGLE_SECRET || ‘DEVELOPMENT’;  process.env.GOOGLE_CALLBACK || ‘’;

config.redis.url=  url.parse(process.env.REDISTOGO_URL || ‘’);

module.exports = config;

Because it’s a standard JavaScript module, when Node.js loads the file it will be executed with the config hash created. This has two important aspects.

Firstly, I can include other helper modules, such as being able to return a parsed url.

Secondly, I can take advantage of the current environment to determine if production or development values should be returned. This is great when combined with Heroku.

With the configuration defined, the logic to access the configuration looks like this:

var config = require(‘./config’)
var id =
var url = config.redis.url

No if statements, no redefining variables, no swapping files around. Clean, simple, effective.

If I wanted to have additional confidence then if NODE_ENV equaled production I could ensure all environment variables are not undefined.

This is working for me, but has anyone found any better solutions? Leave a comment or tweet me @Ben_Hall

Leave a Reply

Your email address will not be published. Required fields are marked *