NodeJS - config cannot not load custom environment variables

djangbahevans picture djangbahevans · May 31, 2018 · Viewed 12.9k times · Source

I am running [email protected] and I am attempting to get settings from the environment variables using .\config\custom-environment-variables.json does not work. However, it reads from the .\config\default.json just fine.

.\config\custom-environment-variables.json

{
  "key": "app_key"
}

.\config\default.json

{
  "key": "defaultKey"
}

running

const config = require('config');
console.log(config.get('key'))

always prints

defaultKey

but prints nothing when I set the key property in config/default to an empty string. How can I resolve this?

What I have tried

  1. Opened a new console anytime I set the environment variable using set app_key=newKey
  2. Set the environment manually

Answer

Peter Grainger picture Peter Grainger · May 31, 2018

The config file name relates to the NODE_ENV environment variable you use when starting node.

The purpose of the module is to have a config file for each type of environment you are deploying to test, staging, prod environments. Default takes over if nothing is set or a file can't be find

e.g. for test and staging environments you would have.

config/default.json

{
  "key": "default_key"
}

config/test.json

{
  "key": "test_key"
}

config/production.json

{
  "key": "prod_key"
}

app.js

var config = require('config')
console.log(config.key)

Then if you run with a different NODE_ENV the same name as the file in the config directory you get the different keys

node app.js // output default_key
NODE_ENV=test node app.js // output test_key
NODE_ENV=production node app.js // output prod_key

You question references custom environment variables using the file config/custom-environment-variables.json This file will enable you to override a value in one of the files with a environment variable set when running node. This is useful when you can't commit the variable, such as database key but might want to access all your config in the same place.

e.g.

{
  "key": "SECURE_DATABASE_KEY"
}

Then running the same program again with the new config file:

NODE_ENV=production node app.js // output prod_key
SECURE_DATABASE_KEY=asldfj40 NODE_ENV=production node app.js // output asldfj40