CodeSampleX

샘플

dotenv 16.6.1: process.env is undefined in an ESM module even though dotenv.config() ran and .env exists

검증된 샘플 — npm dotenv 16.6.1: process.env is undefined in an ESM module even though dotenv.config() ran and .env exists. node 22 · linux alpine/x64 · docker에서…

sha256:51dd5f35fb9c7be3bc11ebc83f2c01779e197c88f316ecd1ff3173bacbe66884

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
4
빌드한 서명 키
3
선언된 환경 node 22 linux x64 node 22 npm

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux alpine/x64 · docker ed25519:a2ec939a4c60e243 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-13
node 22 · linux alpine/x64 · docker ed25519:a2ec939a4c60e243 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-13
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-17
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-09-08

케이스

FIX
목표
process.env is undefined in an ESM module even though dotenv.config() ran and .env exists
패키지
심벌
  • dotenv.config
  • dotenv/config
환경
node 22
생성일
2026-08-13T14:23:25Z

컨트랙트

  1. write a .env at contract time and delete it afterwards
  2. run an entry module that calls dotenv.config() after statically importing a module that reads process.env at import time
  3. assert that import-time capture is undefined, because ESM evaluates the whole import graph before the body runs
  4. assert process.env holds the value after config() returns, proving the .env parsed and only the ordering was wrong
  5. assert the capture is the correct value when 'dotenv/config' is the first import
  6. assert the capture is the correct value when the env-reading module is pulled in by a dynamic import after config()

파일

  • csx.json
  • package-lock.json
  • package.json
  • src/broken.mjs
  • src/fixed-dynamic.mjs
  • src/fixed.mjs
  • src/report.mjs
  • src/settings.mjs
  • test/contract.mjs

소스 아티팩트 내려받기 (tar.gz)

소스

csx.json
{"case":{"caseId":"case:sha256:20465850fa68e5a0d71275e292c73de1f7d8f0ec703d4cf27f5fb8acdb12e2fd","constraints":{"moduleSystem":"esm","runtime":"node"},"contract":["write a .env at contract time and delete it afterwards","run an entry module that calls dotenv.config() after statically importing a module that reads process.env at import time","assert that import-time capture is undefined, because ESM evaluates the whole import graph before the body runs","assert process.env holds the value after config() returns, proving the .env parsed and only the ordering was wrong","assert the capture is the correct value when 'dotenv/config' is the first import","assert the capture is the correct value when the env-reading module is pulled in by a dynamic import after config()"],"goal":"process.env is undefined in an ESM module even though dotenv.config() ran and .env exists","kind":"FIX","packages":["pkg:npm/dotenv@16.6.1"],"schemaVersion":1,"symbols":["dotenv.config","dotenv/config"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","moduleSystem":"esm","os":"linux","packageManager":"npm","runtime":"node","runtimeVersion":"22","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/dotenv@16.6.1"],"schemaVersion":1,"symbols":["dotenv.config","dotenv/config"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "csx-sample-dotenv-esm-load-order",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "csx-sample-dotenv-esm-load-order",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "dotenv": "16.6.1"
      }
    },
    "node_modules/dotenv": {
      "version": "16.6.1",
      "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
      "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",
      "license": "BSD-2-Clause",
      "engines": {
        "node": ">=12"
      },
      "funding": {
        "url": "https://dotenvx.com"
      }
    }
  }
}
package.json
{
  "name": "csx-sample-dotenv-esm-load-order",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "dotenv": "16.6.1"
  }
}
src/broken.mjs
// BROKEN — the exact code that works in CommonJS and silently fails in ESM.
//
// ESM hoists every `import` and evaluates the whole module graph BEFORE a
// single statement of this file's body runs. So `./settings.mjs` reads
// process.env.CSX_DEMO_API_BASE while it is still unset, and captures
// undefined — even though .env exists, is found, and parses fine.
//
// In CommonJS the identical logic works, because `require()` executes at the
// point it appears:
//     require('dotenv').config();          // runs first
//     const { apiBase } = require('./settings.cjs');  // then this
//
// That asymmetry is why this costs people an afternoon: the .env is right
// there, dotenv reports no error, and the value is still undefined.
import dotenv from 'dotenv';
import { apiBase } from './settings.mjs';
import { report } from './report.mjs';

// Runs too late: ./settings.mjs was already evaluated during the hoisted
// import phase above.
dotenv.config();

report('broken', apiBase);
src/fixed-dynamic.mjs
// FIX 2 — keep dotenv.config() explicit (when you need its return value or
// options such as { path }), then reach the env-reading module with a dynamic
// import().
//
// Unlike a static import, `await import(...)` is evaluated at the point it
// appears, so ./settings.mjs is evaluated after process.env is populated.
import dotenv from 'dotenv';
import { report } from './report.mjs';

const result = dotenv.config();
if (result.error) throw result.error;

// Evaluated here, not hoisted — this is what makes the fix work.
const { apiBase } = await import('./settings.mjs');

report('fixed-dynamic-import', apiBase);
src/fixed.mjs
// FIX 1 (preferred) — load dotenv through its side-effect entry point, as the
// FIRST import in the file.
//
// `dotenv/config` calls config() during its OWN evaluation, and static imports
// are evaluated in source order. So process.env is fully populated before
// ./settings.mjs is evaluated, and the import-time read sees the real value.
//
// Keep this import first, and keep it side-effect style — `import dotenv from
// 'dotenv'` followed by dotenv.config() in the body is exactly the broken
// version, because the body runs last. Linters that sort imports
// alphabetically can silently reintroduce the bug.
import 'dotenv/config';
import { apiBase } from './settings.mjs';
import { report } from './report.mjs';

report('fixed-side-effect-import', apiBase);
src/report.mjs
// Prints one sentinel-prefixed JSON line so the contract can read a result
// even when dotenv writes its own banner to stdout.
export function report(name, apiBase) {
  process.stdout.write(
    'CSX_RESULT ' +
      JSON.stringify({
        scenario: name,
        // typeof survives the trip: JSON has no `undefined`.
        capturedType: typeof apiBase,
        captured: apiBase ?? null,
        // Proof that the .env itself was found and parsed: by the time this
        // line runs, process.env IS populated. Only the module-scope capture
        // above happened too early.
        envNow: process.env.CSX_DEMO_API_BASE ?? null,
      }) +
      '\n',
  );
}
src/settings.mjs
// An ordinary config module. It reads process.env once, at import time, and
// exports the value — which is what almost every config/client module does.
//
// Nothing in this file is wrong. The bug is *when* this file gets evaluated
// relative to dotenv.config(). See src/broken.mjs.
export const apiBase = process.env.CSX_DEMO_API_BASE;
test/contract.mjs
import { strict as assert } from 'node:assert';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import fs from 'node:fs';
import path from 'node:path';

const root = fileURLToPath(new URL('..', import.meta.url));
const envPath = path.join(root, '.env');
const KEY = 'CSX_DEMO_API_BASE';
const VALUE = 'https://api.example.test/v1';

// The .env is created here and removed in the finally block below, so the
// sample never ships one. Its only key is a fake URL — nothing secret.
const ENV_FILE = `# Written by test/contract.mjs and deleted when it finishes.\n${KEY}=${VALUE}\n`;

// Each scenario must start from an environment where the key is genuinely
// unset, otherwise "broken" could accidentally pass by inheriting it.
const childEnv = { ...process.env };
delete childEnv[KEY];
assert.equal(process.env[KEY], undefined, 'precondition: key must not be preset');

function run(script) {
  const r = spawnSync(process.execPath, [path.join('src', script)], {
    cwd: root, // dotenv resolves .env against process.cwd()
    env: childEnv,
    encoding: 'utf8',
  });
  assert.equal(r.status, 0, `${script} exited ${r.status}: ${r.stderr}`);
  // dotenv may print a banner of its own, so pick the sentinel line.
  const line = r.stdout.split('\n').find((l) => l.startsWith('CSX_RESULT '));
  assert.ok(line, `${script} printed no CSX_RESULT line. stdout: ${r.stdout}`);
  return JSON.parse(line.slice('CSX_RESULT '.length));
}

fs.writeFileSync(envPath, ENV_FILE);
let broken, fixed, fixedDynamic;
try {
  broken = run('broken.mjs');
  fixed = run('fixed.mjs');
  fixedDynamic = run('fixed-dynamic.mjs');
} finally {
  fs.rmSync(envPath, { force: true });
}

// 1. The bug: a module that reads process.env at import time captures
//    undefined, because ESM evaluated it before dotenv.config() ran.
assert.equal(broken.capturedType, 'undefined');
assert.equal(broken.captured, null);

// 2. ...and it is purely a load-order problem, not a missing/unreadable .env:
//    the same process sees the value in process.env once config() has run.
assert.equal(broken.envNow, VALUE);

// 3. The fix: `import 'dotenv/config'` placed as the first import populates
//    process.env during the import phase, before ./settings.mjs evaluates.
assert.equal(fixed.capturedType, 'string');
assert.equal(fixed.captured, VALUE);

// 4. The other fix: keep dotenv.config() explicit, then pull the
//    env-reading module in with a dynamic import() that runs after it.
assert.equal(fixedDynamic.capturedType, 'string');
assert.equal(fixedDynamic.captured, VALUE);

// 5. The sample ships no .env.
assert.equal(fs.existsSync(envPath), false, '.env must be cleaned up');

console.log(
  'CONTRACT PASS: import-time env read is undefined under dotenv.config(), ' +
    "and correct via `import 'dotenv/config'` or a dynamic import",
);

오리진 시더

anonymous