Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

nodejs
env
variables
communitycreator

How to list all environment variables in Node.Js

Theodore Kelechukwu Onyejiaku

Environment variables are variables that can contain sensitive date in your project. They are variables you wouldn’t want to share with users of your codebase, like api keys, database url, etc. The environment variables also allow applications to behave differently depending on the environment in which the application runs. The environment here could mean your computer, a cloud server, a container, etc.

The process.env

The process.env is a global object that is used to access all the environment variables of the environment your application is running. This means that it is accessible everywhere in our application.

Listing default environment variables with process.env

In the example below, we accessed the process.env object by logging it into the console. Now we can list the default environment variables of our application.

console.log(process.env)

Setting Up Environment Variables

You can set up your environment variables directly in any application file since the process.env is a global object. See an example below:

// Set an environment variable
process.env.AUTHOR_NAME="Theodore";

// Read the variable that was set
console.log(process.env.AUTHOR_NAME);

It might not be the best approach to create your environment variables anywhere in your application. It is better to create the .env file and read the environment variables with dotenv npm package.

Setting up Custom Environment Variables

We want to make sure that we set up our environment variables the proper way and that we are able to read them.

  • First, create the .env file and create the following environment variables:
NAME = Theodore
PLATFORM = Edpresso
  • Second, install the dotenv package and require it in your node starter file, which could be index.js, server.js, app.js or whatever you choose to call it.
require("dotenv").config()

Listing our Environment Variables

Now that we have required the dotenv package in our project starter file, we can access our custom environment variables.

See an example below:

index.js
.env
require('dotenv').config();

console.log(process.env.NAME);   // logs Theodore
console.log(process.env.PLATFORM);  //  logs Edpresso

In the code above, we created our custom environment variables in a .env file and used the dotenv package to be able to read them directly in our index.js file. Now we can list our custom environment variables.

RELATED TAGS

nodejs
env
variables
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring