Grateful Grateful - 2 months ago 6
Node.js Question

Proper use of app.set in express?

I am currently following https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens. However, I do not understand the need for ...

app.set('superSecret', config.secret);


... when you could just continue using
config.secret
. Can someone kindly explain this to me? Much appreciated.

Answer

This simply allows you to access your values via app.settings.superSecret and nothing else.

The good thing about this is, you won't have to keep importing your config object to every file! You can simply grab the value straight from app.settings.

It really comes down to personal choice.

I recommend you read up on the docs over at express: expressjs.com/en/4x/api.html

The reason for a global config file is so you can use specific environments and hide the secret data from say github or bitbucket (some sort of version control service). You wouldn't be uploading your secret details to github, bitbucket, or any other similar service. When I say environments I mean production, development, local, and etc. You could have a function inside your config file that returns a specific objects. E.g

var env = {
  production: {
  ... env vars
  },
  local: {
  ... local vars
  }
}

export default env["production"]; // You would change something here or

Note this is a very basic example of what you could do to change your environment variables. You can simply change env["production"] to env["local"] to swap your environment.