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:
Edit and set environment variables in Postman
Next article icon

Setting up environment variables in Node.js in a platform independent way

Last Updated : 29 Oct, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Environment variables are a good way to ensure security of your precious API keys and secret stuff as well as adaptive code. However, setting up environment variables might be a bit tedious when working on various machines having different Operating Systems. At such times, a portable and project-specific way is needed to use them. Here is a way to configure them using a famous npm module in Node.js.

Step 1: Install dotenv npm package: Open command shell, navigate to the root folder of your project and install dotenv npm package by the following command:

npm install dotenv  

If you prefer yarn, you can do:

yarn add dotenv  

Step 2: Create a file named .env in the root folder of the project which would store all environment variables

Step 3: Require dotenv package in the project

Require dotenv package only on local setups: In the starter JS file of project, which is generally index.js, import the package as early as possible, using this statement:

if(process.env.NODE_ENV !== "production") {      require('dotenv').config();  }  

Here, we import the package only when NODE_ENV is not set to production, which by default is never set. Thereby,
evaluating undefined !== “production” i.e. True, so dotenv is included. However, production servers have their own ways of setting environment variables, so there isn’t an explicit need to use dotenv on published application. When on production, set the NODE_ENV environment variable to production so that dotenv doesn’t get included. For example, Heroku by default sets this variable to production as stated here, so we don’t have to do it manually, check docs of your hosting provider for further details.

Step 4: Setup environment variables inside the .env file and use them just like normal environment variables: Store the key value pairs of environment variables in the .env file in the following format (without any quotes for keys or values):

KEY = VALUE  

For example, your .env file might look like:

DB_KEY = YOUR_ACTUAL_DATABASE_ACCESS_KEY  SECRET_TOKEN = VALUE_OF_YOUR_SECRET_TOKEN  ADMIN_EMAIL = [email protected]  

In your code files, you can use these values by referring to their respective keys, For example,

const my_db_key = process.env.DB_KEY  const adminContactMail = process.env.ADMIN_EMAIL  

Step 5: Ensure that .env file isn’t tracked by git (For security reasons, if you’re using git) If the project has git setup, open the .gitignore file (Create one, if there isn’t), add .env if not present. This prevents it from getting tracked on to public repositories. If you don’t plan to use git with the project, this step can be skipped. You can share and use this .env file on any machine without spending time setting up environment variables.

Note: There are  several other options like, setting custom path for .env files, etc.



Next Article
Edit and set environment variables in Postman
author
omkarphansopkar
Improve
Article Tags :
  • Node.js
  • Web Technologies
  • Node.js-Misc

Similar Reads

  • Reading Environment Variables From Node.js
    Environment Variable: The two fundamental concepts of any programming language are variables and constants. As we know that constants and variables both represent the unique memory locations that contain data the program uses in its calculations. The variable which exists outside your code is a part
    2 min read
  • Environment Variables are Undefined in Next.js App
    Environment variables play a crucial role in web development, especially in configuring sensitive information such as API keys, database URLs, and other configuration settings. If your environment variables are showing up as undefined in your Next.js app, it can disrupt functionality. This issue typ
    3 min read
  • How To Configure And Use Environment Variables in NestJS?
    Environment variables are an important part of application development, allowing developers to configure applications in different environments (development, staging, production) without hardcoding sensitive or environment-specific information into the application code. In this article, we'll walk t
    2 min read
  • How to Load environment variables from .env file using Vite?
    The environment variables in the application are managed through .env files in a Vite project, allowing you to configure and access various settings dynamically. By prefixing variables with VITE_, Vite exposes them to your application’s runtime environment. This approach facilitates different config
    2 min read
  • Edit and set environment variables in Postman
    In Postman, the "environment" refers to a set of key-value pairs or a collection of variables used to customize requests. Environments allow you to define variables that can be reused across multiple requests, making it easier to manage different configurations for testing APIs or web services. Feat
    2 min read
  • How to Use Environment Variables in Vite?
    In order to create your Vite application in different environments such as development, staging and production, you need to use environment variables. They enable you to manage confidential data like API keys or service URLs without having to code them inside your source code. By using environment v
    3 min read
  • What does Double Underscore (__) in Front of a Variable in Node.js ?
    In the world of Node.js, variable naming conventions play a crucial role in code readability, maintainability, and the prevention of naming conflicts. One particular convention that often intrigues developers, especially those new to Node.js, is the use of a double underscore (__) in front of a vari
    3 min read
  • What is the Purpose of __filename Variable in Node.js ?
    In Node.js, there are several global variables that are available in all modules. One such variable is __filename. This article delves into the purpose, usage, and practical applications of the __filename variable in Node.js. What is __filename?The __filename variable is a built-in global variable i
    3 min read
  • Next.js Environment Variables
    Environment variables are a fundamental aspect of modern web development, allowing developers to configure applications based on the environment they are running in (development, testing, production, etc.). In Next.js, environment variables provide a flexible and secure way to manage configuration s
    3 min read
  • Next.js Environment Variables
    In this article, we are going to see how to use environment variables in Next.js. Environment variables in Next.js are a way to set configuration values that are used by your application. They can be used to store data such as the name of your company, the port your application will run on, or any o
    2 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