Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
npm init
Next article icon

NPM dotenv

Last Updated : 10 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Dotenv is a popular npm (Node Package Manager) package used in NodeJS applications to manage environment variables. Environment variables are values that are set outside of an application's code and are accessible to the application during runtime. These variables often contain sensitive information like API keys, database connection strings, or configuration settings.

Prerequisites:

  • NodeJS & NPM
  • JavaScript

Features of dotenv

  • Simplified Loading: dotenv simplifies the process of loading environment variables from a '.env' file into Node.js applications, reducing the need for manual configuration.
  • Improved security: By keeping sensitive information like API keys, database passwords, and other secrets out of your code and in a separate '.env' file, dotenv helps improve security.
  • Compatibility: The package is widely compatible with various Node.js frameworks and libraries, ensuring seamless integration into different types of applications.

Working of dontenv

1. Loading Environment Variables: Dotenv simplifies the process of loading environment variables from a '.env' file into Node.js applications. The '.env' file typically resides in the root directory of the project. It stores key-value pairs of environment variables in a simple format: KEY=VALUE.

_PORT = 3000
API_KEY = localhost
API_PASS= mypassword

2. Parsing and Setting Environment Variables: When you launch your Node.js application, dotenv steps into '.env' file. It reads its contents, and creates individual settings (environment variables) within your program. Through these settings, environment variable are easily accessible throughout your code using process.env.VARIABLE_NAME.

const PORT = process.env.PORT 
const API_KEY = process.env.API_KEY

Now make a Project to show use of dotenv for better understanding.

Approach to Implement dotenv npm

  • We make a node project and install dotenv package. Create a '.env' file and Environment variables as a key-value pair.
  • Integration with Node.js is achieved by importing the dotenv package in the app.js file, and invoked dotenv.config() method. This method reads the .env file, parses its contents, and sets the environment variables in the Node.js runtime environment using process.env. These variables can be accessed throughout the application using process.env.VARIABLE_NAME.

Steps to Setup Application

Step 1: Create a application using the following command:

npm init -y
cd foldername

Step 2: Use npm to install dotenv and express package.

npm i dotenv express 

Step 3: Create a '.env' file in the root directory and set your sensitive or Important variables.

_PORT = 8000
API_KEY = 'XXXXXX'
ACCESS_TOKEN = 'XXXXXXX'

Project Structure:

project-structure
Project Structure

The Updated Dependences in your package.json file is:

  "dependencies": {
"dotenv": "^16.4.5",
"express": "^4.19.2"
}

Example: Below is an example of dotenv npm.

JavaScript
// app.js   const express = require('express') const app = express(); const dotenv = require('dotenv')  // dot env config dotenv.config() const PORT = process.env._PORT; const API_KEY = process.env.API_KEY const ACCESS_TOKEN = process.env.ACCESS_TOKEN   // use these variable according to your nedd   // Server  app.listen(PORT, () => {     console.log(`Server is Running on PORT No.  ${PORT}.`) }) 
JavaScript
// .env _PORT = 8000 API_KEY = 'XXXXXX' ACCESS_TOKEN = 'XXXXXXX' 

Start your application using the following command:

node app.js

Output

npm dotenv output
Output

Next Article
npm init

S

sandeepxt99
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Node-npm

Similar Reads

  • npm run dev
    When working with Node.js and JavaScript projects, especially those involving frontend frameworks like React, Vue, or Next.js, you often encounter the command npm run dev. This command is pivotal for developers as it initiates the development server, enabling live reloading, hot module replacement,
    3 min read
  • npm init
    NPM (Node Package Manager) is the default package manager for Node and is written entirely in JavaScript. Developed by Isaac Z. Schlueter, it was initially released on January 12, 2010. NPM manages all the packages and modules for Node and consists of command line client npm. NPM gets installed into
    3 min read
  • npm completion command
    The npm completion command provides a way to enable shell completion for npm commands, making it easier to use the npm CLI by suggesting commands and arguments as you type. This can save time and reduce the risk of making typos, especially when dealing with long command names or package names. Prere
    3 min read
  • Important npm Commands
    Node Package Manager (npm) stands at the core of JavaScript development, serving as a robust package manager for handling dependencies, project initialization, and script execution. Understanding the essential npm commands is important for managing dependencies and automating tasks. In this article,
    3 min read
  • npm doctor command
    The npm doctor command is one of the features available in npm with the primary purpose of performing a health check on your npm environment, it evaluates if the general condition of the npm that is being used is in accordance with the general norms. Syntax: npm doctorThese are the following topics
    3 min read
  • npm bin Command
    The npm bin command is a lesser-known but incredibly useful command in the Node.js ecosystem. It provides information about the location where npm installs globally executable binaries or locally installed binaries for the current project. In this article, we’ll explore the details of the npm bin co
    4 min read
  • npm ping Command
    npm ping command is a simple but powerful utility provided by npm to check if your npm registry is accessible, this command allows developers to verify the connection between their projects and the NPM registry, it sends a request to the registry and returns a response indicating whether the registr
    3 min read
  • Node.js nodemon npm Module
    The nodemon npm Module is a module that develop node.js based applications by automatically restarting the node application when file changes in the directory are detected. Nodemon does not require any change in the original code and method of development. Advantages of Using nodemon Module: It is e
    1 min read
  • NuxtJS Deployment
    In this article, we are going to learn how we can deploy our NuxtJS app on Vercel. Nuxt.js is a free and open-source web application framework based on Vue.js, Node.js, Webpack, and Babel.js. Nuxt is inspired by Next.js, which is a framework of similar purpose, based on React.js. Nuxt gives you the
    2 min read
  • Pygal Dot Chart
    Pygal library in Python is an open-source library used for data visualization. We can draw various interactive plots and charts using different datasets. For example, bar charts, line charts, pie charts, radar charts, etc. Install Pygal in PythonTo draw a dot chart using Pygal in Python. We need the
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences