Nconf – simple, great solution for Node.js app configuration

When I started work with Node.js and Express, I was looking for something to store my app settings. Something like env files in many PHP frameworks – central place for configuration, not stored in repository, but only for example when we run app in development or production environment. We can write custom code for that, or use some modules from npm, also directly for env files. Nuxt package also has dedicated env file module. These modules are great, but there is something much, much better – nconf.

Yes, nconf it’s another module from npm, available also on Github. It’s not only configuration storage tool to simply create files similar to env, but powerful mechanism to use many different configurations in one place. First important difference – with env file or env modules, we can create simple key – value pairs in configuration file. With nconf, we can use JSON file… so there is no problem with hierarchical structure, nested objects, arrays etc. – the different database configurations in one file but depended on environment? No problem! Load configuration from remote source? Also not problem.

Nconf installation is of course very simple using npm:

npm install nconf --save

After that, we can use nconf in our app, there is simple example:

var nconf = require('nconf')

I do not want to copy all Github documentation. This blog post is only short information about this nice module and recommendation – because nconf is very elastic and can be used in many cases. There are some important capabilities of this module:

  • Get config from json file, from other files, from command line arguments IN ONE TIME (yes, you can use nconf to get values from file and args)
  • Create default settings – they can be, but not must to be overwritten by other config sources
  • Create overwrite setting – other places can’t overwrite these settings
  • Required settings – script can throw error if there are missing settings
  • Stores – something like settings “boxes”, each with different configurations. You can simply move between boxes using “use” method
  • Saving – nconf can not only read settings, but also writes new data to setting sources

I think these possibilities make nconf a great choice. It’s also actively developed and stable, so… If you know better option (or options), let me know!