Luke Oliff.

TIL: Managing Environment Variables With .env Files in Node.js

·TIL·1 min read·Luke Oliff

Hardcoding API keys in source code is a bad habit that every developer has to unlearn. The dotenv package makes it easy.

npm install dotenv

Create a .env file in your project root.

VONAGE_API_KEY=abc123
VONAGE_API_SECRET=xyz789
PORT=3000

Load it at the top of your entry file.

require('dotenv').config()

const apiKey = process.env.VONAGE_API_KEY

.env files are not committed to git. Add .env to your .gitignore. Each developer on the team creates their own with their own keys.

What about .env.example?

Commit a .env.example file with placeholder values. It documents what variables the project needs without exposing real secrets.

Does dotenv work with async code?

dotenv runs synchronously at startup. Call it before any other require or import and process.env will be populated.