Solution 1:

-> For node version 18.x and below 18.x
-> To install and configure dotenv in a Node.js project, you can follow these steps:

Step 1: Install dotenv

Open your terminal and navigate to your Node.js project’s root directory. Then, run the following command to install dotenv using npm:

– npm install dotenv

Step 2: Create a .env File

Create a file named .env in your project’s root directory. This file will contain your environment variables. For example:

– DB_HOST=localhost
– DB_USER=myuser
– DB_PASSWORD=mypassword

Step 3: Configure dotenv in Your Node.js Application

Create an entry point file for your application (e.g., app.js, server.js, etc.), and add the following lines at the top of the file:

– require(‘dotenv’).config();

This will load the environment variables from the .env file and make them available to your Node.js application.

Step 4: Access Environment Variables

Now, you can access the environment variables in your application using process.env. For example:

– const dbHost = process.env.DB_HOST;
– const dbUser = process.env.DB_USER;
– const dbPassword = process.env.DB_PASSWORD;

Solution 2:

– for node version 20.x LTS

Starting from Node.js v20.6.0, Node.js supports .env files for configuring environment variables.

Your configuration file should follow the INI file format, with each line containing a key-value pair for an environment variable. To initialize your Node.js application with predefined configurations, use the following CLI command: node –env-file=config.env index.js.

For example, you can access the following environment variable using process.env.PASSWORD when your application is initialized:
– PASSWORD=nodejs

In addition to environment variables, this change allows you to define your NODE_OPTIONS directly in the .env file, eliminating the need to include it in your package.json.

OR you can go through official node v20.6.0 release note.

Support On Demand!