Languages
[Edit]
EN

Node.js - how to use .env

0 points
Created by:
Rian-Whitehouse
469

In this article, we would like to show you how to use .env in Node.js.

Introduction

The .env file is used to store environment variables. Environment variables are used to protect the sensitive data (like API keys) that shouldn't be visible directly in the code.

2. Setup dotenv and create .env file

To use environment variables, install dotenv package with the following command in the console:

npm install dotenv

Import dotenv in your project and use dotenv.config() to make it work.

const dotenv = require('dotenv');
dotenv.config();

The next step is to create .env file. Below you can see the example project structure.

/app/
  ├── node_modules/
  ├── .env
  ├── index.js
  ├── package-lock.json
  └── package.json

3. Set environment variables

There are two ways of setting the environment variables.

1. Directly in .env file:

Node.js - set environment variables
Node.js - set environment variables

Note:

The # in .env file is used for comments.

2. From the code:

const dotenv = require('dotenv');
dotenv.config();

// Set DB_NAME environment variable
process.env['DB_NAME'] = 'myDatabase';

4. Access environment variables

To access keys and values you defined in your .env file use the process.env.

Practical example:

const dotenv = require('dotenv');
dotenv.config();

// get database name from .env file
console.log(process.env.DB_NAME);

Output:

exampleDB
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join