Skip to main content
Environment variables are the secure way to pass configuration and secrets to your Node.js application. Hardcoding database passwords or API keys directly in code is a critical mistake that exposes them in version control. This page teaches you to use 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 through process.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

Never hardcode these values directly in your JavaScript files. Anyone with access to the git repository, including everyone who ever commits in the future, can read every value in git history, even if you later delete the file.

Installing and Using dotenv

Create your .env file in the project root:
Load it at the very top of your entry file (app.js or index.js):
Access variables anywhere:

.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.
Onboarding a new developer:

.gitignore: Protecting Secrets

The !.env.example line explicitly ALLOWS .env.example to be committed even though all other .env.* files are excluded.

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 scatter process.env.X throughout your code. Use a config module:
Use it:

Production Secret Management

For production, avoid .env files on the server. Use:

Key Terms

Common Mistakes

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.
Without .env.example, new developers don’t know what variables to set. They will get mysterious crashes with no guidance.
Scattering process.env.X through 50 files makes refactoring and testing very hard. A config module centralizes and validates everything.
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”))’