Node.js6 min read

Environment Variables in Node.js (dotenv)

Learn to manage configuration with environment variables. Use dotenv for secure secrets management.

Sarah Chen
December 19, 2025
0.0k0

Environment Variables in Node.js

Environment variables store configuration outside your code. Essential for secrets.

Why Environment Variables?

// ❌ Never do this
const apiKey = 'sk-secret-key-12345';

// ✅ Use environment variables
const apiKey = process.env.API_KEY;

Accessing Environment Variables

// Access any env variable
console.log(process.env.PATH);
console.log(process.env.HOME);
console.log(process.env.NODE_ENV);  // 'development' or 'production'

Setting Variables (Command Line)

# Single command
PORT=3000 node app.js

# Multiple variables
PORT=3000 NODE_ENV=production node app.js

# Windows (PowerShell)
$env:PORT=3000; node app.js

Using dotenv Package

Install:

npm install dotenv

Create .env file:

# .env
PORT=3000
DATABASE_URL=mongodb://localhost/mydb
API_KEY=your-secret-key
DEBUG=true

Load in your app:

// app.js - Load at the very top!
require('dotenv').config();

console.log(process.env.PORT);        // 3000
console.log(process.env.API_KEY);     // your-secret-key

.env File Best Practices

# Use comments for documentation
# Database Configuration
DATABASE_URL=mongodb://localhost/mydb
DATABASE_NAME=myapp

# API Keys
STRIPE_KEY=sk_test_...
SENDGRID_KEY=SG....

# Feature Flags
ENABLE_CACHE=true
DEBUG_MODE=false

Don't Commit .env!

Add to .gitignore:

# .gitignore
.env
.env.local
.env.*.local

Create .env.example for documentation:

# .env.example (commit this)
PORT=3000
DATABASE_URL=your_database_url_here
API_KEY=your_api_key_here

Different Environments

// Load different files based on environment
const envFile = process.env.NODE_ENV === 'production' 
  ? '.env.production' 
  : '.env';

require('dotenv').config({ path: envFile });

Type Conversion

Environment variables are always strings:

// .env: PORT=3000

const port = process.env.PORT;       // "3000" (string!)
const port = parseInt(process.env.PORT, 10);  // 3000 (number)

// Booleans
const debug = process.env.DEBUG === 'true';  // boolean

Required Variables Check

const required = ['DATABASE_URL', 'API_KEY', 'JWT_SECRET'];

for (const key of required) {
  if (!process.env[key]) {
    console.error(`Missing required env variable: ${key}`);
    process.exit(1);
  }
}

Config Module Pattern

// config.js
require('dotenv').config();

module.exports = {
  port: parseInt(process.env.PORT, 10) || 3000,
  db: {
    url: process.env.DATABASE_URL,
    name: process.env.DATABASE_NAME || 'myapp'
  },
  jwt: {
    secret: process.env.JWT_SECRET,
    expiresIn: '7d'
  },
  isDev: process.env.NODE_ENV !== 'production'
};
// app.js
const config = require('./config');

app.listen(config.port);

Key Takeaway

Use environment variables for all secrets and configuration. Install dotenv, create .env file, add it to .gitignore, and load with require('dotenv').config() at the top of your entry file. Create a config module for clean access.

#Node.js#Environment Variables#dotenv#Configuration#Beginner