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.google = {};
config.redis = {};


config.google.id = process.env.GOOGLE_ID || ‘DEVELOPMENT.googleusercontent.com’;
config.google.secret=  process.env.GOOGLE_SECRET || ‘DEVELOPMENT’;
config.google.callback=  process.env.GOOGLE_CALLBACK || ‘http://127.0.0.1:3000/google/callback’;


config.redis.url=  url.parse(process.env.REDISTOGO_URL || ‘http://127.0.0.1:6379’);


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 = config.google.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 *