How to add environment variables in nodejs

There are many things that have to be kept a secret, exposing certain details can comprise the application and can make it vulnerable.

It is a best practice to keep the credentials and secrets aside from the code base, it should not be stored in any files.

One of the safe places to store and access variables from are the environment variables of the operating system.

For every server-side rendered application, we can keep the secrets in the operating system and can access it.

The same goes for Nodejs.

In the production mode, we can directly access the environment variables from the process object.

For example,

process.env.PORT // this will return the PORT's value from the environment variable of Operating System.

On the local, we will have to use the dotenv package.

Install it,

npm install dotenv --save

And then create a .env file in your root folder and have all the environment variables here.

PORT = 3000

Now using the dotenv we can access it in our local application. Load the dotenv if not in production mode.

if (process.env.NODE_ENV !== "production") {
  require("dotenv").config();
}

and then we can use the environment variables locally as well.

process.env.PORT // 3000