Chapter 7 of 12
Environment variables are configuration values set outside the application. They're the standard way to handle secrets (API keys, database passwords), and settings that differ between development and production.
WARNING
Never hardcode secrets in source code. API keys, database passwords, and tokens in source code get committed to git and exposed forever. Environment variables keep secrets out of your codebase. This is not optional β it's a fundamental security practice.
// Node.js makes environment variables available on process.env
const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;
const nodeEnv = process.env.NODE_ENV; // "development" or "production"
// Set them when starting the server
// PORT=4000 node server.js# .env β never commit this to git!
PORT=3000
DATABASE_URL=mongodb://localhost:27017/myapp
JWT_SECRET=super-secret-key-change-in-production
API_KEY=sk-abc123
# .env.example β commit this (with placeholder values)
PORT=3000
DATABASE_URL=your-database-url-here
JWT_SECRET=your-secret-here
API_KEY=your-api-key-here// Install: npm install dotenv
// In your entry point (very first line)
require("dotenv").config();
// or: import "dotenv/config"; (ES modules)
// Now process.env has your .env values
const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;
if (!dbUrl) {
console.error("DATABASE_URL is required");
process.exit(1); // exit with error code β don't start without it
}