7

Actually I have a nodejs express app with its config file for params like host, port, JWT token, DB params and more.

The question is if it could have sense to keep those params directly on environment variables (whitout any config file) and acces them without the need of do the "require" for config in all components and modules.

All examples I see uses a config file, probably something about security or memory?

CVO
  • 702
  • 1
  • 13
  • 31

3 Answers3

5

A config file lets your very quickly set the entire environment of a machine - eg S3 buckets, API urls, access keys, etc. If you separate these into separate process.env.VARIABLE then you would need to set each of these...for which you would likely make a script...and now you have an environment file again!

To access environment variables you can use process.env.VARIABLE in your nodejs code (is always a string), as long as the variable is set before the process is started.

Tobin
  • 1,698
  • 15
  • 24
  • Also it would be easier to dockerize the app later – Jay Jan 25 '19 at 10:35
  • Ok good point about the config file utility. So the idea will be to have the config file and at the begining of the code pass all parameters to proccess.env.Parametername instead of doing the require to access to config file directly (with lots of requires). If there is no problem about security having the keys (secret, and db) on environment variables, this will be the right solution for me. – CVO Jan 25 '19 at 11:16
5

config file is usually for setting the default values for your environment variables,

which is needed when you are writing the test cases and need to use default values or mock values,

and also you will have all the env variables at one place which is better management.

so if you have an environment variable x,

in config file you can keep it as

config.x = process.env.x || 'defaultVale or mockValue'

AZ_
  • 3,094
  • 1
  • 9
  • 19
3

Another possibility is using an .env files in nodejs. I think you have to npm install dotenv in your application. Ideally different instances (dev, prod....) have its own .env file, and you dont have to call require("dotenv") every time if you want to access the environment variable. Call it in the very beginning i.e) in app.js and you can access the environment variable in any of the sub-files.

Walter
  • 80
  • 5
  • Thanks, very interesting, I didn't know that module – CVO Jan 25 '19 at 11:15
  • Interestingly, the maintainers of dotenv [discourage the use of multiple .env files](https://www.npmjs.com/package/dotenv#should-i-have-multiple-env-files), while popular frameworks like [Vue CLI](https://cli.vuejs.org/guide/mode-and-env.html#environment-variables) do just that. – Aposhian May 29 '20 at 20:00