NodeJs Environment variables vs config file NodeJs Environment variables vs config file express express

NodeJs Environment variables vs config file


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'


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.


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.