Node.js: how do I read environment variables from a .env file?

poze 5 months ago114 gadeen

2

process.env.DATABASE_URL is undefined even though it's in my .env file. Do I still need the dotenv package?

Anviwònman:Node.js 22Node.js 22

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

poze 5 months ago

1 Repons

8
✓
✓ Repons yo aksepte

Node doesn't read .env automatically. Since Node 20.6 you have a built-in flag, so you no longer need dotenv:

node --env-file=.env server.js
# optional file, no error if missing (Node 22+)
node --env-file-if-exists=.env server.js

Or in code (Node 21.7+): process.loadEnvFile().

On older Node versions, import 'dotenv/config' at the very top of your entry file still works.

Don't forget: add .env to .gitignore and commit a .env.example with placeholder values.

Konekte pou di lòt moun si li te mache.

answered 5 months ago

Sign in and verify your email to post an answer.