How to use Node Environment Variables with a dotenv file in Node.js

Programming, error messages and sample code > Node.js
Environment variables are supported out of the box with Node and are accessible via the env object (which is a property of the process global object.)
To see this in action, you can create your own environment variable right in the Node REPL by appending a variable to the process.env object directly.
For example, to create an environment variable to store the ApiKey, you could assign the variable like this: process.env.API_KEY=“12345” in your JS file.

How to Use dotenv
dotenv is a lightweight npm package that automatically loads environment variables from a .env file into the process.env object.

To use dotenv, first install it using the command:

npm i dotenv

 Then in your app, require and configure the package like this:

require('dotenv').config()

How to Create a .env File
Once you have dotenv installed and configured, make a file called .env at the top level of your file structure. This is where you will create all of your environment variables, written in the NAME=value format. For example, you can declare multiple variables in the .env file, set database-related environment variables like this:

DB_HOST=mysql50xx.site4now.net
DB_USER=your_db_user
DB_PASSWORD=password

There is no need to wrap strings in quotation marks, dotenv does this automatically for you.
 
Please do NOT set the PORT environment variable, since IISNODE will use a dynamic port with proxy, just set your application codes to
 
listen(process.env.PORT)

How to Access the Environment Variables

Accessing your variables is super easy! They are attached to the process.env object, so you can access them using the pattern process.env.KEY.  
If you ever need to change the value of any of your environment variables, you just need to alter the .env file.