How to read environment variables with Node.js

by Matt Heff

Node.js is a fast, scalable, and efficient framework in the web development community, known for its event-driven, nonblocking input/output structure. Node.js also has a convenient way of working with environment variables, allowing for easy configuration of a Node.js application

How to check you have Node.js installed on your machine

node -v

If it is installed you will see the version number returned, if node is not present you will get a error form the command line which is equivalent of saying

Gary Coleman Whatchu Talkin Bout Willis GIF - Gary Coleman Whatchu Talkin  Bout Willis Confused - Discover & Share GIFs

How to install Node.js

  1. Go to the Node.js Downloads page.
  2. Download Node.js for your Operating System
  3. Run the installer, including accepting the license, selecting the destination, and authenticating for the install.

Now when you open a new console and run node -v the command line will return the version you just installed

Using Node.js to access environment variables two Methods

1 – Access the environment variables already present

In Node.js, you can easily access variables set in your computer’s environment. When your Node.js program starts, it automatically makes all environment variables available through an “env” object. You can see the object by running the command “node” in your command line and then typing “process.env”.

You should see something like this

If we want to access a specific parameter, lets use SHELL for example we would want to run a command such as

console.log(`Shell is parameter is ${process.env.SHELL}`);

With this you can check what variables exist within the environment, you can update them, add some but these will only be available to that individual node process and any children it spawns. This is easy to access but it is not the best when you are working on multiple projects and need to specify environmental variable settings per project. For that we have another approach

2 – Access Environmental Variable using DOTENV

Dotenv is a module in Node.js allows you to easily load environment variables from a .env file in your project. This file should contain key-value pairs, with the keys being the names of the environment variables and the values being the values you want to set for those variables. Once you have your .env file set up, you can use the dotenv module to load the variables into your Node.js application. You will want to keep sensitive information in here examples of such items are API keys, besides that you can use it for anything else you don’t want to hard-code into your application.

Important: If you use git or other version controls make sure you do not include .env in version tracking. The last thing you need is this sensitive data pushed into a repo for someone to exploit.

Installing dotenv
npm install dotenv --save

After it has been installed, add the following line to the top of your js file


Create a .env File

After this is installed, you need to make a file called .env and put it in the top level of your projects file / folder structure. This file is the place to put all your environmental variables. When entering your variables there is no need to wrap strings in quotation marks, DotEnv does this automatically for you, below is an example .env file.

Example .env file contents

A example of a DB connection using the DB_HOST parameter

const dotenv = require('dotenv');
const { Client } = require('pg');

// Load environment variables from .env file

// Get the value of the DB_HOST environment variable
const serverName = process.env.DB_HOST;

// Create a new PostgreSQL client
const client = new Client({
  host: serverName,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,

// Connect to the database
  .then(() => console.log(`Connected to PostgreSQL on ${serverName}`))
  .catch(err => console.error(`Error connecting to PostgreSQL at ${serverName}: ${err}`));

Once you have done this and saved it to a file (eg env-example.js) then run the file and see what happens

node env-example.js

Depending if you have an actual postgres Db that you can access with username/pass/database with the values above you will either see

Connected to PostgreSQL on

Error connecting to PostgreSQL at Error: getaddrinfo ENOTFOUND

Other Issues — Package PG not found

If your environment does not have the required postgres package then you can installed it by using the following

npm install pg --save


Woo Hoo!! We have just learned and hopefully experimented two methods for using environmental variables in Node.js: dotenv and directly from the environment. Armed with this knowledge you can now easily store and access any information your projects in a secure and convenient way.

Have fun with it.

Related Posts