dotenv properly, validate variables at startup, and structure your project to never leak secrets.
What Are Environment Variables
Environment variables are key-value pairs managed at the operating system level. Node.js applications read them throughprocess.env. They exist outside your code, which means:
- They differ per deployment (dev, staging, production) without code changes
- They are not committed to version control
- They can be changed without redeploying (with a server restart)
What Belongs in .env
Installing and Using dotenv
.env file in the project root:
app.js or index.js):
.env File Format
.env.example: The Template File
.env.example is a copy of .env with placeholder values instead of real secrets. It IS committed to git and shows developers what variables they need to configure.
.gitignore: Protecting Secrets
NODE_ENV
NODE_ENV is the standard variable for controlling application behavior:
Validating Environment Variables at Startup
Fail loudly at startup if required variables are missing. This is better than failing mysteriously later.Centralized Config Module
Never scatterprocess.env.X throughout your code. Use a config module:
Production Secret Management
For production, avoid.env files on the server. Use:
Key Terms
Common Mistakes
Committing .env to git
Committing .env to git
This is the most critical mistake. If your .env is in git history, rotate ALL secrets immediately. Simply deleting the file does not remove it from history.
Not creating .env.example
Not creating .env.example
Without .env.example, new developers don’t know what variables to set. They will get mysterious crashes with no guidance.
Using process.env directly throughout codebase
Using process.env directly throughout codebase
Scattering process.env.X through 50 files makes refactoring and testing very hard. A config module centralizes and validates everything.
Using short JWT secrets
Using short JWT secrets
JWT_SECRET=‘secret’ or JWT_SECRET=‘password’ can be brute-forced. Generate a long random string: node -e ‘console.log(require(“crypto”).randomBytes(32).toString(“hex”))’