Get Environment Variable in Node.js

Contents
In this article, you will learn how to get environment variable in Node.js.
Getting environment variable in Node.js
Environment variables are a fundamental concept in Node.js applications, allowing developers to set configuration parameters that are accessible throughout the application.
Setting Environment Variables
Before you can retrieve an environment variable, you need to set it. In Node.js, you can set environment variables using the process.env object. Here’s an example:
process.env.NODE_ENV = 'production';
process.env.DB_NAME = 'mydatabase';
Retrieving Environment Variables
Once you’ve set an environment variable, you can access it using the process.env object. Here’s an example:
const envVar = process.env.DB_NAME;
console.log(envVar); // Output: 'mydatabase'
Note that environment variables are always returned as strings. If you need to use a variable as a number or boolean, you’ll need to convert it manually.
Using Default Values
If an environment variable is not set, you can use a default value instead. Here’s an example:
const port = process.env.PORT || 3000;
console.log(port); // Output: 3000 if PORT is not set
This code sets the port variable to process.env.PORT if it exists, otherwise it uses the default value of 3000.
Using dotenv
If you have a lot of environment variables to set or want to keep them in a separate file, you can use the dotenv package. First, install it using NPM:
npm install dotenv
Then, create a .env file in your project’s root directory and add your environment variables:
NODE_ENV=production
DB_NAME=mydatabase
Finally, load the environment variables using dotenv.config():
require('dotenv').config();
Now you can access the environment variables as usual using process.env.