🔍 What Are Environment Variables?

Environment variables are key-value pairs used to store configuration settings outside of your code.

Example:

// Accessing an environment variable
console.log(process.env.PORT);

This prints the value of the PORT variable if it is set in the environment.

📂 Why Use Environment Variables?

⚙ How to Set Environment Variables

1️⃣ Setting Directly in the Terminal

Example:

# Setting a variable for one command
PORT=3000 node app.js

Explanation: This sets the PORT variable only while running node app.js.

2️⃣ Using a .env File with dotenv Package

Example:

# .env file
PORT=3000
API_KEY=abcdef123456
// Using dotenv
require('dotenv').config();
console.log(process.env.API_KEY);

dotenv reads the .env file and loads the values into process.env.

🔒 Best Practices for Environment Variables

📝 Summary

In Node.js, environment variables store sensitive and configurable information outside your code, keeping it secure and adaptable. You can set them directly in the terminal or manage them with a .env file and the dotenv package. By following best practices, you ensure security, flexibility, and consistent behavior across environments.