Environments in a node.js application

One of the important issue in all web applications is having different environments for different uses. In particular, you’ll probably want to have different environments for development, testing, and production. I ran into this issue when I first started writing tests for an app I’m working on (sidenote: turns out testing is fun). At the time, the database connection was going to the development db, which isn’t what you want for contained testing. After searching around for a while, and after finding a bunch of different ways to handle the configuration, I settled on the following implementation.

var production = {
    database: {
         url : 'mongodb://localhost/worldpic'
     }
};
var development = {
    database: {
      url : 'mongodb://localhost/worldpic'
    }
};
var test = {
    database: {
        url : 'mongodb://localhost/worldpic_test'
    }
};
module.exports = function () {
     switch(process.env.NODE_ENV){
        case 'production':
             return production;
        case 'development':
             return development;
        case 'test':
             return test;
        default:
             return development;
     }
};

This file I called config.js and I put that in the config folder (so config/config.js). The other thing you could do, and something that I might in the future, is split the environment variables into their own files in the config folder and require them in the config.js file.

With this done, you can get a config object by running in app.js (or server.js if that’s your style)

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

From there, you can access the desired database url by running

config.database.url

The same syntax would be used for any environment variable that you might want, such as external api keys.

The last part is actually setting the NODE_ENV variable. This is done from the command line when you run node or mocha (for testing)

NODE_ENV=test mocha

for example, or

NODE_ENV=development npm start

You don’t actually need to specify the env if you’re using development since it defaults to that, but being specific is always good.

And that’s it! Structured configuration for node that’ll make your life way easier.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s