Master Code
On The Go

Learn. Practice. Build.

Home › How-To › Environment Variables with dotenv

Node.js Guide

Environment Variables with dotenv

Never hardcode API keys or database passwords again. Here's how to use .env files in Node.js the right way.

Quick answer: Install dotenv (npm install dotenv), create a .env file with KEY=value lines, add require('dotenv').config() at the top of your entry file, then read values via process.env.KEY. Add .env to .gitignore.

1

Install dotenv

npm install dotenv

Add it to your project dependencies. It's a small package with zero sub-dependencies.

2

Create a .env File

In your project root, create .env:

PORT=3000
DATABASE_URL=postgres://user:pass@localhost:5432/mydb
OPENAI_API_KEY=sk-abc123
NODE_ENV=development

Rules for .env files:

  • One KEY=value per line
  • No spaces around the =
  • No quotes needed (they become part of the value)
  • Comments start with #
3

Add .env to .gitignore

Critical: NEVER commit .env to Git. It contains secrets. Add it to .gitignore immediately.

# .gitignore
node_modules/
.env
.env.local
.env.*.local

Instead, commit a .env.example with fake values that documents what variables are needed:

# .env.example
PORT=3000
DATABASE_URL=postgres://user:pass@localhost:5432/mydb
OPENAI_API_KEY=sk-your-key-here
NODE_ENV=development
4

Load .env at Startup

CommonJS:

require('dotenv').config();

console.log(process.env.PORT);  // "3000"

ES Modules:

import 'dotenv/config';

console.log(process.env.PORT);

The import 'dotenv/config' form runs dotenv as a side effect — you don't need to call .config() manually.

💡 Must be the FIRST import in your entry file. Otherwise other code might read process.env before it's populated.

5

Use Environment Variables

const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;
const apiKey = process.env.OPENAI_API_KEY;

// Validate required variables at startup
const required = ['DATABASE_URL', 'OPENAI_API_KEY'];
for (const key of required) {
    if (!process.env[key]) {
        console.error(`Missing required env var: ${key}`);
        process.exit(1);
    }
}

Always check required variables at startup. Better to fail fast than to crash later.

6

Native Alternative (Node 20.6+)

Recent Node versions have dotenv-like support built in:

node --env-file=.env app.js

No package needed. Works exactly the same as dotenv. Use this for new projects on Node 20+.

You can also specify per-environment files:

node --env-file=.env.production app.js

🛡️ Security Best Practices

❓ Frequently Asked Questions

What is dotenv?

An npm package that loads environment variables from a .env file into process.env.

Should I commit .env?

Never. Add it to .gitignore. Commit .env.example instead.

Do I need dotenv in Node 20+?

No. Use node --env-file=.env app.js instead — it's built in.

Different .env files per environment?

Create .env.development, .env.production. Load with --env-file or dotenv's path option.

🎯 What's Next?

← All How-To Guides