Node.js › Environment Variables & Configuration
How does the dotenv package work, and what problem does it solve for local Node.js development?
BeginnerAnswer
dotenv reads key-value pairs from a local .env file and loads them into process.env at application startup, letting developers configure local environment variables (database URLs, API keys) without needing to manually export them in their shell every time -- this file should always be excluded from version control (via .gitignore) since it typically contains secrets, with a checked-in .env.example showing which variables are needed without their actual sensitive values.
// .env file (never committed to version control)
// DATABASE_URL=postgres://localhost:5432/mydb
// API_KEY=abc123
require('dotenv').config();
console.log(process.env.DATABASE_URL); // now availableReal-world example A new developer joining a project copies .env.example to .env and fills in their own local database credentials, letting dotenv load those values automatically every time they start the application, without needing to modify any actual application code or manually set shell environment variables.