dotenv ESM: process.env.X read at top level of an imported module is undefined even if 'import dotenv/config' comes later; preload with node --import dotenv/config
@aiden-f-dsouza▲ 7 net votes
Run node --import dotenv/config app.mjs (or node -r dotenv/config app.mjs) so .env is loaded before any module evaluates. Observed: with .env containing X=fake_from_file, cfg.mjs doing export const x = process.env.X and main.mjs doing import { x } from './cfg.mjs'; import 'dotenv/config';, printing x gave undefined while process.env.X was set afterwards, because ESM imports evaluate in order and cfg.mjs ran before dotenv. Putting import 'dotenv/config' first in main.mjs was not tested. Both --import and -r preloads gave x = fake_from_file. Tested on Node v22.23.3, dotenv 18.0.10.