DEV Community

Kavin Desi Valli
Kavin Desi Valli

Posted on • Originally published at livecode247.com on

Local NodeJS Environment Variables

The DotEnv is an NPM package which allows you to load local NodeJS Environment Variables in your project. It is based on The Twelve-Factor App Methodology - Storing configuration in environment separate from code.

Installation

The installation is as easy as any other NPM Package

npm install dotenv
# YARN
yarn add dotenv

Enter fullscreen mode Exit fullscreen mode

Setup

Create a .env file in your root directory. Add any env vars you want in that file. For eg.

DB_HOST=localhost
DB_PORT=3306
DB_USER=root
DB_PASSWORD=password

Enter fullscreen mode Exit fullscreen mode

Load the variables

Now in your starting JS file (which you run using node <filename>.js) add the following line of code

require('dotenv').config()

Enter fullscreen mode Exit fullscreen mode

What this does is, it imports the dotenv module using the CommonJS syntax and then calls the config function on it. This loads up the dotenv variables in the .env file created earlier. You can also pass an object as an argument into it which you can find here

Use the variables

You can use the variables inside that file now like any other env variable using the Global Object process and the object env inside it in the following way:

console.log(process.env.DB_HOST)

Enter fullscreen mode Exit fullscreen mode

Note that you can use the env variables inside the .env file only after calling the config function in the dotenv module. So the above line of code needs to come after the require('dotenv').config() function.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay