CVO
CVO

Reputation: 742

NodeJs Environment variables vs config file

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?

Upvotes: 7

Views: 8761

Answers (3)

arizafar
arizafar

Reputation: 3122

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'

Upvotes: 5

Tobin
Tobin

Reputation: 2018

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.

Upvotes: 5

Walter
Walter

Reputation: 82

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.

Upvotes: 3

Related Questions