Chovy's Blog

Web Development with Node.js, PHP, Javascript, and HTML5

By

Managing config variables inside a Node.js application

In the interest of avoiding debate over this post, let’s just say there is more than one way to skin a cat when it comes to configuration management in an application. Some like to keep it out of the code base, others prefer it. This method stores the config files in the repository.

There is more than one way to handle configuration variables based on an environment for a node.js app, but I’ve come up with a pretty simple solution that keeps my config variables DRY and complete control to override them at the same time using different node environments.

The basic premise is to set a NODE_ENV environment variable before you start your node app, then use that variable to load a matching config.whatever.js file. So if you start your app with NODE_ENV=test node ./app.js then you will load config.test.js file that overrides a config.global.js file….more on that in a second.

Here’s the basic config/index.js file, this will load the config.test.js file assuming your NODE_ENV=test (we will default to ‘development’ if NODE_ENV is not defined):

Next comes the config.test.js which will include config.global.js and then overwrite it’s json objects as needed:

config.test.js:

And the config.global.js which defines all the defaults:

Now we wrap it all together and use it in our code…for example in a model, you might do something like this in ./models/user.js:

And that’s all there is to it.
You just need need to be sure you define all your defaults in ./config/config.global.js and overwrite based on the environment in ./config/config.<env>.js .

Be sure to start your app with any of the following (I usually have test, production and development environments):

  • chovysblog

    People have different ideas on how configuration management should be handled. Here’s an example from Eric Elliot on Geekli.st — he suggested not checking environment data into your repository and instead loading a shell script that has all the sensitive info like db hostnames and passwords.