Facebook Pixel

What Is dotenv and Why Use It in Node.js Environment Variable Management

Learn what dotenv is, why environment variables are essential for Node.js applications, and how to securely manage credentials like API keys, database URIs, and JWT secrets.

What Is dotenv and Why Use It in Node.js?

Environment variables are the standard way to manage configuration and secrets in Node.js applications. The dotenv package loads them from a .env file into process.env.

What Are Environment Variables?

Environment variables are key-value pairs stored outside your code. They configure your app without changing code:

PORT=3000 MONGODB_URI=mongodb://localhost:27017/devtinder JWT_SECRET=my_super_secret_key NODE_ENV=development

Why Use Environment Variables?

  1. Security Never commit secrets (passwords, API keys) to Git
  2. Configuration Different settings for development, staging, production
  3. Portability Same code runs everywhere with different .env files
  4. 12-Factor App Environment variables are a core principle of modern app design
  5. Team collaboration Each developer has their own .env with local settings

What Is dotenv?

dotenv is an npm package that loads environment variables from a .env file into process.env:

npm install dotenv
// At the top of your entry file (server.js or app.js) require("dotenv").config(); console.log(process.env.PORT); // 3000 console.log(process.env.JWT_SECRET); // my_super_secret_key

The .env File

Create a .env file in your project root:

# Server PORT=3000 NODE_ENV=development # Database MONGODB_URI=mongodb://localhost:27017/devtinder # Authentication JWT_SECRET=your_jwt_secret_here JWT_EXPIRES_IN=7d # AWS SES SES_HOST=email-smtp.us-east-1.amazonaws.com SES_PORT=587 SES_USER=AKIAXXXXXXXXX SES_PASS=your-smtp-password # Frontend CLIENT_URL=http://localhost:5173

.env.example File

Always create a .env.example file (committed to Git) with placeholder values:

# .env.example (committed to Git) PORT=3000 NODE_ENV=development MONGODB_URI=mongodb://localhost:27017/devtinder JWT_SECRET=replace_with_your_secret SES_HOST=email-smtp.us-east-1.amazonaws.com SES_PORT=587 SES_USER=replace_with_your_ses_user SES_PASS=replace_with_your_ses_password CLIENT_URL=http://localhost:5173

New developers copy it: cp .env.example .env and fill in their values.

.gitignore

Never commit .env to Git:

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

If you accidentally commit .env:

git rm --cached .env echo ".env" >> .gitignore git commit -m "Remove .env from version control"

Using dotenv with Different Environments

// Load environment-specific .env const env = process.env.NODE_ENV || "development"; require("dotenv").config({ path: `.env.${env}` });

Files:

  • .env.development Local development
  • .env.staging Staging server
  • .env.production Production server

dotenv Best Practices

  1. Load early require("dotenv").config() at the top of your entry file
  2. Never commit .env Add to .gitignore
  3. Use .env.example Template with placeholder values
  4. Validate required vars Fail fast if missing
  5. Use descriptive names MONGODB_URI not DB
  6. Don't overload Keep only config and secrets, not business logic
  7. Type-cast values parseInt(process.env.PORT) not process.env.PORT

Validating Environment Variables

// src/config/env.js const requiredEnvVars = [ "PORT", "MONGODB_URI", "JWT_SECRET", "NODE_ENV" ]; const validateEnv = () => { const missing = requiredEnvVars.filter(varName => !process.env[varName]); if (missing.length > 0) { throw new Error(`Missing required environment variables: ${missing.join(", ")}`); } }; validateEnv();

The Takeaway

dotenv loads environment variables from a .env file into process.env, keeping secrets out of your code. Always create a .env.example template, add .env to .gitignore, load dotenv early in your entry file, validate required variables, and use descriptive names. Environment variables are essential for security, configuration, and the 12-factor app methodology.

dotenv is an npm package that loads environment variables from a .env file into process.env. Install with npm install dotenv, then call require('dotenv').config() at the top of your entry file. This keeps secrets like database URIs, JWT secrets, and API keys out of your code.

For security (never commit secrets to Git), configuration (different settings for dev/staging/prod), portability (same code runs everywhere with different .env files), 12-factor app compliance, and team collaboration (each developer has their own .env with local settings).

Add .env to your .gitignore file. Also add .env.local and .env.*.local. If you accidentally committed .env, run git rm --cached .env, add it to .gitignore, and commit. Always create a .env.example with placeholder values for new developers.

Configuration and secrets only: PORT, NODE_ENV, MONGODB_URI, JWT_SECRET, API keys (AWS, Stripe, etc.), email credentials, and client URLs. Don't put business logic, non-secret config that's the same everywhere, or large data. Use descriptive names like MONGODB_URI not DB.

Create a list of required variable names, check if each exists in process.env, and throw an error listing all missing ones. This fails fast at startup instead of failing later with a confusing error when a missing variable is accessed.

Ready to master Node.js completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.