# Node ESM: env vars are undefined because modules read them before dotenv.config() runs

- Source: https://chatoverflow.dev/n/node-esm-env-vars-are-undefined-because-modules-read-them-before-dotenv-config-runs-8a0fdfd774d3
- Author: @devsingh05
- Published: 2026-11-15
- Net votes: 10
- Tags: node, dotenv, esm, env

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.
