100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Node.js

Environment Variables and Configuration

Learn how to manage configuration and secrets in Node.js apps using environment variables and dotenv.

Deployment & Best PracticesBeginner8 min readJul 8, 2026
Analogies

Introduction

Real-world applications need different configuration values depending on where they run — a local machine, a staging server, or production. Environment variables let you inject values like database URLs, API keys, and feature flags into your app at runtime without hardcoding them into source code. Node.js exposes environment variables through the global process.env object, and the dotenv package makes it easy to load them from a local file during development.

🏏

Cricket analogy: A team's playing eleven changes depending on the venue — a spin-friendly pitch in Chennai versus a pace-friendly one in Perth — and process.env is like the team management pulling the right lineup for wherever they're playing, without rewriting the entire squad list.

Syntax

javascript
// .env file (kept out of version control)
PORT=3000
DATABASE_URL=mongodb://localhost:27017/myapp
JWT_SECRET=supersecretvalue
NODE_ENV=development

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

const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;
const isProduction = process.env.NODE_ENV === 'production';

console.log(`Starting server on port ${port} (production: ${isProduction})`);

Explanation

dotenv.config() reads the key-value pairs from a .env file in the project root and copies them into process.env, where the rest of your application can read them. This file should NEVER be committed to source control because it typically contains secrets such as database credentials, API keys, and signing secrets. Instead, add .env to .gitignore and commit a .env.example file listing the required variable names with placeholder values, so other developers know what to configure. In hosting environments like Docker, Heroku, or a VPS, environment variables are usually set directly through the platform's configuration (dashboard, docker-compose.yml, or systemd service files) rather than a .env file, since the platform injects them into the process environment automatically.

🏏

Cricket analogy: dotenv.config() is like a physio reading a confidential player fitness file before the match and briefing the coach privately — that file (.env) never gets handed to the media (.gitignore), though a public team-sheet template (.env.example) shows what info is tracked; on match day at an international venue, the board's official system (hosting platform) supplies player data directly instead of a locally kept file.

Example

javascript
// config.js — centralize and validate configuration
require('dotenv').config();

function requireEnv(name) {
  const value = process.env[name];
  if (!value) {
    throw new Error(`Missing required environment variable: ${name}`);
  }
  return value;
}

module.exports = {
  port: process.env.PORT || 3000,
  databaseUrl: requireEnv('DATABASE_URL'),
  jwtSecret: requireEnv('JWT_SECRET'),
  nodeEnv: process.env.NODE_ENV || 'development',
};

Output

If DATABASE_URL is missing from the environment, the app throws Error: Missing required environment variable: DATABASE_URL immediately at startup instead of failing later with a confusing connection error. This 'fail fast' pattern catches misconfiguration early, before the app accepts any traffic, which is far easier to diagnose than a runtime crash triggered by a user request.

🏏

Cricket analogy: If the pitch report is missing before the toss, a well-run team refuses to walk out and bat blind rather than discovering mid-innings that they don't know the conditions — catching the missing information before a single ball is bowled, not after a batting collapse.

Key Takeaways

  • process.env exposes environment variables to a running Node.js process.
  • The dotenv package loads variables from a local .env file into process.env during development.
  • .env files must be added to .gitignore and never committed — they often contain secrets.
  • Commit a .env.example file so teammates know which variables to set without exposing real values.
  • Validate required configuration at startup so the app fails fast with a clear error instead of failing later.

Practice what you learned

Was this page helpful?

Topics covered

#NodeJs#NodeJsExpressStudyNotes#WebDevelopment#EnvironmentVariablesAndConfiguration#Environment#Variables#Configuration#Syntax#StudyNotes#SkillVeris