🔍 What Are Environment Variables?
Environment variables are key-value pairs used to store configuration settings outside of your code.
- They are like hidden settings for your app.
- They keep sensitive data (like API keys, passwords) out of your code.
- They allow you to change settings without editing the actual 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?
- Security: Keeps sensitive information out of source control.
- Flexibility: Easily change settings between development, testing, and production.
- Portability: Makes your code work on different machines without changes.
⚙ 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
- Create a .env file in your project root.
- Add your variables there.
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
- Never commit .env files to public repositories.
- Use different .env files for development and production.
- Document all required variables in a .env.example file.
📝 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.