Using nconf to configure a Node.js application

Introduction

Sometimes things vary from environment to environment. Like, we wear a tie to the office but try not to elsewhere. Similarly in Node.js, you might want configuration settings to change per environment. Some of these settings include IP address, port number, database configurations etc., that change from the development to production environment. The recommended approach for changing your app’s environment is by using the NODE_ENV environment variable.

Currently, Node.js does not have a standard way of managing config variables, but luckily there are a number of node modules that help you standardize this. One among them is the nconf package. Nconf provides a hierarchical Node.js configuration, with files, command-line arguments, and environment variables.

Sometimes we will refer configuration settings as settings/configurations.

Storing local configuration data

The simplest approach for storing the configuration for a Node.js app generally involves having an object stored as a JSON on the file system. This can be easily done using the JSON.parse and JSON.stringify methods.

In the above case nconf.get(‘httpPort’) will return 3000 since default configurations are being loaded first.

Note: Both nconf.defaults() and nconf.overrides() loads given configuration values into the configuration hierarchy. The first declared config value will always take precedence over others.

We can conclude that the configurations which are loaded first will take higher priority over others.

Why set it up this way?

The biggest benefit is to support multiple environments without having to manually change values on every deployment. Your command line arguments and environment variables will defer from server to server and need to be setup only once, whereas the config.json file might be pushed into your version control and remain same across servers. Values from config.json will only be loaded if certain values are not already present in the environment variables or not passed via command line arguments.

Summary

Nconf is a simple node module that provides us a robust way to get configuration information into our Node.js apps. It collects data from the host environment, command line arguments, and even multiple configuration files through a simple interface. This allows developers and admins to configure their application in any way they want based on the environment.

Posted By:Sindhusha B, Osmosee

Are you interested? follow us and get notified of new posts

Follow

3 thoughts on “Using nconf to configure a Node.js application”

> “The config items that were loaded later will override any previous item ….”
This is not what I found, when I tested earlier values took precedence.
Eg. If my config.json is { test: ‘test’ } and I have process.env[‘test’] = ‘environment’.
Then I do:
nconf.env().file( ‘config.json’ );
console.log( nconf.get( ‘test’ ) ); // outpus: environment