Node.js Environment Variables: process.env, dotenv & --env-file
How to use environment variables in Node.js. Covers process.env, dotenv, Node 20.6+ --env-file flag, NODE_ENV, type-safe validation with zod, and cross-platform support.
Last updated:
Frequently Asked Questions
How do I read environment variables in Node.js?
Use process.env.KEY which returns the value as a string, or undefined if not set. All environment variable values are strings — you need to parse numbers, booleans, and JSON manually.
What is the --env-file flag in Node.js?
Node.js 20.6+ includes a built-in --env-file flag that loads .env files without any third-party package: node --env-file=.env app.js. It supports comments and basic syntax but not variable expansion.
What is NODE_ENV and why does it matter?
NODE_ENV is a convention (not a Node.js built-in) that indicates the runtime environment. Libraries like Express and React use it to toggle behavior: "production" enables optimizations, "development" enables verbose logging and dev tools.
Stay up to date
Get notified about new guides, tools, and cheatsheets.
Related Cheatsheets
Cheatsheet
JSON Cheat Sheet — Syntax, Parsing & Common Mistakes
Quick reference for JSON syntax: data types, objects, arrays, JSON.parse/stringify, jq basics, and common mistakes like trailing commas and single quotes.
Cheatsheet
JavaScript Cheat Sheet — ES6+ Quick Reference
JavaScript ES6+ quick reference: destructuring, spread operator, arrow functions, array methods, promises, async/await, and modules.
Cheatsheet
TypeScript Cheat Sheet — Types & Generics Quick Reference
TypeScript quick reference: basic types, interfaces, generics, utility types, type guards, enums, and type assertions.
Related Guides
dotenv Not Loading? Step-by-Step Debugging Guide
Fix environment variables not loading from .env files. Covers Node.js, Python, Docker, file path issues, syntax errors, load order, and production gotchas.
The Complete .env File Syntax Reference
Definitive reference for .env file syntax: quoting rules, comments, multiline values, variable expansion, and differences across Node.js, Python, Ruby, Go, and Docker Compose.
Python Environment Variables: os.environ, dotenv, and Pydantic
How to read, set, and manage environment variables in Python. Covers os.environ, python-dotenv, Pydantic Settings, Django, and Flask patterns.