Environment Variables in Node.js

📘 Node.js 👁 52 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

Environment variables are external values used to configure applications without changing source code.
They are commonly used to store sensitive information and environment-specific settings.


1. Why Environment Variables Are Important

  • Keep secrets out of source code

  • Support different environments (development, testing, production)

  • Improve security

  • Simplify configuration management

Examples:

  • Database URLs

  • API keys

  • Port numbers


2. Accessing Environment Variables in Node.js

Node.js provides the process.env object.

console.log(process.env.PORT);

3. Setting Environment Variables

3.1 On Windows

set PORT=3000 node app.js

3.2 On macOS / Linux

export PORT=3000 node app.js

4. Using Environment Variables in Code

const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server running on port ${port}`); });

5. Using .env Files (dotenv Package)

Managing many environment variables manually is difficult.
The dotenv package loads variables from a .env file.


Install dotenv

npm install dotenv

Create .env File

PORT=4000 DB_URL=mongodb://localhost:27017/appdb

Load Environment Variables

require('dotenv').config();

6. Using Environment Variables with Express.js

const express = require('express'); require('dotenv').config(); const app = express(); const PORT = process.env.PORT; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });

7. Environment-Based Configuration

if (process.env.NODE_ENV === 'production') { // production settings } else { // development settings }

8. Security Best Practices

  • Never commit .env files to Git

  • Add .env to .gitignore

  • Use strong secret values

  • Rotate secrets regularly


9. Common Environment Variables

VariablePurpose
PORTServer port
NODE_ENVApp environment
DB_URLDatabase connection
API_KEYExternal service key

10. Common Mistakes

❌ Hardcoding secrets
❌ Forgetting to load dotenv
❌ Using wrong variable names


11. Summary

  • Environment variables store configuration data

  • Accessed via process.env

  • dotenv simplifies management

  • Essential for secure Node.js applications


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes