Last Updated: February 25, 2016
·
5.427K
· chrisbumgardner

Automatic per-environment config in Node.js

Something I find myself doing commonly on my node/express projects is keeping separate config properties files per environment (e.g. 'development', 'production', etc). Here's a gist to how I've implemented a simple module which loads the appropriate file based on the current NODE_ENV and returns it as the config object: https://gist.github.com/4076234. It expects to have files 'development.js' and 'production.js', for example, in the same directory. Then when you run node as follows:

> NODE_ENV=production node app.js

You can access your config object like so:

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

And 'config' will contain everything in ./config/production.js. Note in a production environment you would probably start node using 'forever' or similar (that's what I use), but regardless this still works. Then for example if you export 'mongodb.host' in your config files, you can access it via:

config.mongodb.host

This will return the mongodb host for the current environment. If node is launched without an explicit environment, it defaults to 'development'. If an environment is specified and there's not a corresponding <env>.js file in the ./config directory it throws an exception.

An example of this in a project: https://github.com/cbumgard/node-boot. Look at ./app.js, ./config/index.js, ./config/development.js, and ./config/production.js to see specifics.