How to Set Up Environment Variables in Nodejs

By onjsdev

Jan 29th, 2024

Setting up environment variables in Node.js is a common practice to manage configuration settings and sensitive information in your applications. Here's a beginner's guide on how to set up environment variables in Node.js:

Step 1: Create a New Node.js Project

If you don't have a Node.js project yet, create one using the following commands:

mkdir my-node-project
cd my-node-project
npm init -y

Step 2: Install dotenv Package

The dotenv package is commonly used to load environment variables from a file. Install it using:

npm install dotenv

Step 3: Create a .env File

Create a file named .env in the root of your project. This file will store your environment variables. For example:


Step 4: Load Environment Variables in Your Node.js Code

In your main Node.js file (e.g., index.js), load the environment variables using dotenv. Add the following lines at the top of your file:


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

Step 5: Access Environment Variables

Now you can access your environment variables throughout your code using process.env. For example:

const dbHost = process.env.DB_HOST;
const dbPort = process.env.DB_PORT;
const secretKey = process.env.SECRET_KEY;

console.log(`Database Host: ${dbHost}`);
console.log(`Database Port: ${dbPort}`);
console.log(`Secret Key: ${secretKey}`);


  • Security: Do not commit your .env file to version control systems like Git. It contains sensitive information.
  • Defaults: You can provide default values in case an environment variable is not defined. For example:
const dbHost = process.env.DB_HOST || 'localhost';
  • Multiple Environments: You can have different .env files for different environments (e.g., .env.development, .env.production). Set the NODE_ENV variable to specify the environment.

Then, load the environment-specific file:

const envFile = `.env.${process.env.NODE_ENV || 'development'}`;
require('dotenv').config({ path: envFile });


That's it! You've successfully set up environment variables in your Node.js project. Adjust the variable names and values according to your specific needs

Thank you for reading.