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

Edit

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

Edit

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

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

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

3. Set environment variables

Edit

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:

4. Access environment variables

Edit

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

Practical example:

Output:

 

See also

Edit
  1. Node.js - read .env file (custom solution) 
  2. Node.js - common way to pass environment variables to Node.js process (Windows, Linux, macOS, etc.)

1
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