Open In App

How to handle environment variables in Node ?

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Environment variables are dynamic values that can affect the behavior of NodeJS applications across different environments such as development, staging, and production. Managing environment variables properly is essential for configuring applications, connecting to databases, and controlling application behavior. Here’s how you can handle environment variables in NodeJS effectively:

1. Using process.env:

NodeJS provides access to environment variables through the process.env object. This object contains key-value pairs of environment variable names and their corresponding values. You can access environment variables like any other object property:

const port = process.env.PORT || 3000;
console.log(`Server listening on port ${port}`);

2. Configuration Files:

Create configuration files (e.g., .env) to store environment-specific variables. Use libraries like dotenv to load environment variables from these files into process.env:

require('dotenv').config();
console.log(process.env.DB_HOST);

3. Command-Line Arguments:

Pass environment variables as command-line arguments when running NodeJS applications. These arguments can be accessed using process.argv:

node app.js --env=development
const env = process.argv.find(arg => arg.startsWith('--env=')).split('=')[1];
console.log(`Running in ${env} environment`);

4. Environment-Specific Configurations:

Maintain separate configuration files for different environments (e.g., development, staging, production). Load the appropriate configuration based on the environment:

const config = require(`./config.${process.env.NODE_ENV}.js`);
console.log(config.db.host);

5. Using Environment Variables in Packages:

Some packages, such as express, mongoose, and sequelize, allow you to configure settings using environment variables directly:

const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});

Conclusion:

Handling environment variables in NodeJS is crucial for configuring applications across different environments. Whether using process.env, configuration files, command-line arguments, environment-specific configurations, or package-specific settings, it’s essential to manage environment variables securely and efficiently to ensure the robustness and flexibility of NodeJS applications.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads