What is dotenv in node js?

dotenv or .env is configuration file in node js which can read environment variables. It is defined in root directory. .env stores configuration variables , like port no, api keys, database credentials etc. All the important and secure data is stored in .env file.

Environment variables can vary based on different environment, like development, staging and production. By using a .env file, its is easy to many environment variables of different different stages.


Install dotenv

dotenv is available on npm as dotenv.

npm i dotenv

Configure dotenv

Once the dotenv is installed, next step is to configure dotenv in node js application. To do this, include dotenv using require() or import in ES Modules and then call the config function. See example below.


require("dotenv").config();


import 'dotenv/config'
    

Environment variables

Now we can add some environment variables in .env file. The variables in .env files are defined followed by assignment operator and then its value.


    PORT=3000
    API_KEY=1234567890
    DATABASE_URL=mongodb://127.0.0.1/dbname

Read Variables in express

To read variables from .env, use process.env in application.


const express=require("express");
const app=express();
require("dotenv").config();

const port = process.env.PORT || 3000;
        
    
app.listen(port,()=>{ 
    console.log(`App running at http://127.0.0.1:${port} `)
});    

dotenv in Node JS 20.6.0 and above

Node JS 20.6.0 and above has build-in support of .env files. This means, we don't need to download dotenv from npm. This can enhance security and make our code simple and cleaner.

To read environment variables without dotenv modules, add --env-file=.env between node and app.

node --env-file=.env src/app