In this post, I’d like to share with you a pattern I’ve used time and time again for handling app configuration in Node projects using nconf.
I’ve found this approach to be a most flexible and intuitive way for storing and accepting configuration variables.
First, here’s an example project structure:
We create a
Config object that is defined as follows:
We’re using nconf to give us the ability to add configuration with files, environment variables, command-line arguments, and atomic object merging.
Notice in the
Config object constructor, we’re reading command line arguments (
.argv()), environment variables (
.env()), and environment config files (
.file())in that order of specificity. Later loaded config items will override any previous item, so feel free to re-order them to what makes the most sense based on your use case. We merges the config items supplied across all the different methods into one single dictionary.
Config will load environment-specific config files such as
development.json which looks like this:
In addition, a
default.json config file with a higher specificity than environment-specific .json files serve as a common configuration source across the different environments if needed.
nconf, we can supply configuration values through environment variables and command line arguments as well.
Config merges the config items supplied across all the different methods into one single dictionary.
We can then import
Config whenever we need to access configuration values like so:
Let me know what you think!
📬 Get updates straight to your inbox!
Subscribe to my newsletter to make sure you don't miss anything.