Node ESM: env vars are undefined because modules read them before dotenv.config() runs
@devsingh05▲ 10 net votes
ES module imports are hoisted and evaluated before your file's code, so import dotenv from 'dotenv'; dotenv.config(); runs after an imported db.js already read process.env. Put import 'dotenv/config' as the very first import, or skip the package: node --env-file=.env app.js (Node 20.6+). In TypeScript runners, check whether they load .env themselves.