Categories
JavaScript Nodejs

Using dotenv Node Package to Read Environment Variables

Spread the love

We can use the dotenv Node package to read environment variables into our Node app.

To install it, we run:

npm i dotenv

Then in our .env file, we add:

DB_HOST=localhost
DB_USER=root
DB_PASS=password

In index.js, we write:

require('dotenv').config();
console.log(process.env);

Then we get something like the following from the console log output"

{
  NODE_VERSION: '12.16.2',
  HOSTNAME: 'f99aa86838ab',
  YARN_VERSION: '1.22.4',
  HOME: '/home/runner',
  PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
  NODE_PATH: '/usr/local/lib/node_modules:/home/runner/node_modules',
  PWD: '/home/runner',
  TERM: 'xterm-256color',
  DB_HOST: 'localhost',
  DB_USER: 'root',
  DB_PASS: 's1mpl3'
}

As we can see, we have the environment variable values stored in the process.env object.

Now we can use them in whatever way we wish to.

We can also change where the environment variables are read from and the encoding of the text of the .env file.

For instance, we can change the path of the file as follows:

require('dotenv').config({ path: './env.test' });

Now dotenv will read from .env.test.

We can also change the encoding to read the text file with by writing:

require('dotenv').config({ encoding: 'latin1' });

This is the most popular package for reading environment variables and since it’s this easy to use, we know why it’s the case.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *