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
// .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
// 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
1. Which global object does Node.js use to expose environment variables to a running application?
2. What is the primary purpose of the dotenv package?
3. Why should a .env file never be committed to version control?
4. What is a recommended practice for helping teammates know which environment variables an app requires?
Was this page helpful?
You May Also Like
Deploying Node.js Apps
Understand process managers, containerization, and common hosting options for deploying Node.js applications.
Securing Express Apps (Helmet, CORS, Rate Limiting)
Harden Express applications with secure HTTP headers, controlled cross-origin access, and rate limiting to mitigate common attacks.
Setting Up a Node.js Environment
Install Node.js, choose an LTS version, and configure a basic project structure ready for development.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebSockets Study Notes
Web Development · 30 topics
Web DevelopmentWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentSpring Boot Study Notes
Java · 30 topics
Web DevelopmentFlask Study Notes
Python · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics