Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to Node.js
Node.js Environment Variables and dotenv

Node.js Environment Variables and dotenv

Node.js2,635 viewsBy Admin
nodejsenvironmentvariablesdotenv

Why Environment Variables?

Environment variables store configuration and secrets (API keys, DB URLs) outside your code — keeping them safe and configurable per environment.

Accessing Them

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

Using a .env File

# .env
PORT=4000
DATABASE_URL=mongodb://localhost/myapp
API_KEY=secret123
// Load it (Node 20+ has built-in support)
require("dotenv").config();
console.log(process.env.PORT); // 4000

Node 20.6+ Built-in

node --env-file=.env index.js  # no dotenv package needed

Critical Security Rule

# .gitignore
.env   # NEVER commit secrets to Git!

FAQs

Where should secrets go in production?

In your host's environment settings (Vercel, AWS), not in files. More in our Node.js guides.

Why not hardcode config?

It exposes secrets and makes per-environment config impossible.