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

posée 5 months ago118 vuesen

2

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

Environnement :Node.js 22Node.js 22

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 5 months ago

1 réponse

8
✓
✓ Réponse acceptée

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.

Connectez-vous pour dire si ça a marché.

answered 5 months ago

Sign in and verify your email to post an answer.