environment variable setup in Nodejs

to setup the environment variable through dotenv module

firstly install dotenv module


npm install dotenv

Now create the .env file in the root folder of your project

in the .env file put the below code

Write the credentials


DB_HOST=localhost
DB_USER=root
DB_PASS=12sdf
DB_NAME=myportal

Now include the env module in your main file like server.js


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

// Now, get the envorment credentials through


process.env.enviormentVariableName like "process.env.DB_HOST"

include the environment credentials into server.js


var MongoClient = require('mongodb').MongoClient;
 
var url = `mongodb://${encodeURIComponent(process.env.DB_USER)}:${encodeURIComponent(process.env.DB_PASS)}@localhost:27017/process.env.DB_NAME`;

// Connect to the db
MongoClient.connect(url, function (err, db) {
    
     if(err) throw err;
 
     console.log("Database connected");
                 
});

environment variable setup in Nodejs – Interview Questions

Q 1: What are environment variables?

Ans: Environment variables store configuration values outside the application code.

Q 2: Why use environment variables?

Ans: For security and environment-specific configurations.

Q 3: How do you access environment variables?

Ans: Using process.env.

Q 4: What is dotenv?

Ans: A package that loads environment variables from a .env file.

Q 5: What should not be stored in environment variables?

Ans: Sensitive data should be protected and never exposed publicly.

Related environment variable setup in Nodejs Topicss