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

asked 5 months ago118 viewsen

2

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

Environment:Node.js 22Node.js 22

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 5 months ago

1 Answer

8
✓
✓ Accepted answer

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.

Sign in to tell others whether this worked.

answered 5 months ago

Sign in and verify your email to post an answer.