ERR_REQUIRE_ESM and __dirname Is Not Defined in ESM Projects
require of an ESM-only package has nothing to load, and ESM creates none of the CommonJS wrapper globals. Dynamic import, createRequire, and the path replacements.

Introduction & Quick Summary
Symptom. Two errors that usually arrive together. Adding a package to a CommonJS service breaks startup: Error [ERR_REQUIRE_ESM]: require() of ES Module /app/node_modules/node-fetch/src/index.js from /app/index.js not supported. Or, after adding "type": "module" to package.json, the first file that uses a path fails with ReferenceError: __dirname is not defined in ES module scope — and often require is not defined beside it.
Cause. ERR_REQUIRE_ESM means your CommonJS file is require()ing a package that publishes only an ESM entry, and the condition require has nothing to load. The second is the opposite direction of the same change: ES modules have no __dirname, __filename, require or module, because those are CommonJS wrapper variables that ESM scope never creates — import.meta.url replaces them.
Fix. For the import: await import() from CommonJS, or convert the file to ESM; on Node 22.12+ require() of an ESM module without top-level await works natively, so upgrading is the smallest change. For the paths: use import.meta.dirname (Node 20.11+), or fileURLToPath(new URL('.', import.meta.url)) where you must support older runtimes, and createRequire(import.meta.url) when you still need require.
Core Mechanics, Signatures & Reproducible Setup
The failing shape and the fixed one side by side:
// index.js — CommonJS because package.json has no "type"
const fetch = require('node-fetch'); // ERR_REQUIRE_ESM: node-fetch 3 is ESM-only
const path = require('node:path');
const file = path.join(__dirname, 'data.json'); // fine in CJS// index.mjs — ES module
import { readFile } from 'node:fs/promises';
import path from 'node:path';
const here = import.meta.dirname ?? path.dirname(new URL(import.meta.url).pathname);
const data = JSON.parse(await readFile(path.join(here, 'data.json'), 'utf8'));
const { default: fetch } = await import('node-fetch'); // only when you must stay lazyFor a large CommonJS codebase, the least invasive fix is createRequire, which restores a require bound to the module's own resolution context:
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const require = createRequire(import.meta.url);
const pkg = require('./package.json'); // JSON and CJS deps both work
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const __filename = fileURLToPath(import.meta.url);createRequire returns a real CommonJS require with resolve, cache, and main, so libraries that expect CJS keep working. It cannot load an ESM-only package, because that is the same limitation.
Key Comparison Table
| Global | CommonJS | ES module |
|---|---|---|
__dirname | Available | import.meta.dirname (Node 20.11+), or fileURLToPath |
__filename | Available | import.meta.filename (Node 20.11+) |
require() | Available | createRequire(import.meta.url) |
module.exports | Available | export / export default |
import.meta.url | undefined (or via a shim) | Available |
Top-level await | No | Yes |
| Path resolution | Adds extensions, index files | Exact specifier, no guessing |
this at top level | module.exports | undefined |
| Package situation | require() from CJS | Fix |
|---|---|---|
"type": "module", exports.import only | ERR_REQUIRE_ESM on Node < 22.12 | await import(), or upgrade Node |
ESM with top-level await | Fails even on 22.12+ | await import() only |
Dual package (import + require) | Works, but two instances | Check for state duplication |
exports without a require condition | ERR_PACKAGE_PATH_NOT_EXPORTED | Use the documented entry |
| ESM-only dependency deep import | ERR_PACKAGE_PATH_NOT_EXPORTED | Not exposed; use the public entry |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. __dirname in a CLI that walks up to the project root
import.meta.dirname is the directory of the current module; walking up works exactly as before, and process.cwd() is the wrong substitute because it depends on where the user ran the command:
import path from 'node:path';
const root = path.resolve(import.meta.dirname, '..'); // package root, not cwdIf the file is bundled, import.meta.url can point inside the bundle; bundlers offer their own replacement (__dirname is still injected by webpack in output formats that support it).
2. require of a JSON file in ESM
import data from './data.json' with { type: 'json' } is the standard syntax and is supported in Node 22 with the attribute; without it Node throws ERR_IMPORT_ATTRIBUTE_MISSING. The createRequire route avoids the attribute entirely and is the pragmatic choice for config files:
const require = createRequire(import.meta.url);
const config = require('../config/app.json');3. ERR_REQUIRE_ESM inside a dependency you cannot change
A CJS library requires an ESM-only package internally and throws from its own code. You cannot patch node_modules durably; pick one of three real options: upgrade the library to a version that supports ESM, move your code to ESM so the chain stays ESM, or pin the ESM-only package to an older CJS major in overrides/resolutions while you migrate.
{
"overrides": { "node-fetch": "^2.7.0" } // temporary, forces the CJS release
}4. TypeScript emitting the wrong module format
"module": "esnext" with "type": "commonjs" produces import statements in .js files that Node parses as CJS: SyntaxError: Cannot use import statement outside a module. The tsconfig and the type field must agree, or the output extension must decide it (.mjs/.cjs).
{
"compilerOptions": {
"module": "nodenext", // follows package.json "type"
"moduleResolution": "nodenext",
"verbatimModuleSyntax": true
}
}5. Tests that lose __dirname after the migration
Jest runs CJS by default and fails on ESM with Cannot use import statement outside a module; enabling --experimental-vm-modules and extensionsToTreatAsEsm works but needs import.meta handling. Vitest and node:test are simpler for new ESM code, and node --test needs no configuration at all:
node --test --experimental-test-coverage6. ESM entry points that resolve differently
import.meta.resolve('pkg') returns a URL string, not a path, and does not check that the file exists in all versions. Convert before fs calls, and never concatenate a raw file: URL:
import { fileURLToPath } from 'node:url';
const entry = fileURLToPath(import.meta.resolve('some-pkg'));Common Compilation/Runtime Mistakes & Version Gotchas
"type": "module"added globally. Every.jsin the package becomes ESM at once, including test helpers and config files that usemodule.exports. Convert incrementally with.mjs, or settypeper package.- Assuming Node 22
require(esm)covers everything. A module with top-levelawaitstill throwsERR_REQUIRE_ASYNC_MODULE; the error names the module, andawait import()is the only route. __dirnameshims copied from old blog posts.path.dirname(fileURLToPath(import.meta.url))works;new URL('.', import.meta.url).pathnamebreaks on Windows (/C:/…) and on paths with spaces (%20).module.exportsleft in place after conversion. It becomes aReferenceErrorin ESM; a mixed file that needs both is a sign to split it.- Bundled dependencies in serverless output. A bundler may inline an ESM-only package into CJS, which works until it uses top-level
await. Check the platform's module format instead of guessing. exportsmaps hide files you used to import. After a dependency addsexports,pkg/dist/x.jsdeep imports throwERR_PACKAGE_PATH_NOT_EXPORTED. Use the documented entry point.- Dynamic
import()in CJS returns a namespace object. Named exports are on the object, and the default export is under.default; a directrequire-style usage silently gets the wrong shape (a common cause offetch is not a function).
Related tools. Encode or decode the file: URLs that appear in ESM stack traces with the URL encoder, format the package.json exports block before comparing two versions with the JSON formatter, and diff a converted file against its CommonJS original with the text diff so a dropped export shows up immediately.
Try matching browser tools
All toolsSmall utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Node.js guides
All Node.js guidesNode.js fetch ETIMEDOUT and SELF_SIGNED_CERT_IN_CHAIN Debugging
fetch failed hides everything in error.cause. Read the aggregate, trust the private CA the way curl does, route the proxy, and set the connect timeout undici does not.
Node.js JavaScript heap out of memory: Snapshots and Real Leaks
Distinguish needs more from leaks before raising the flag: external memory and heap tell different stories, and a heap ceiling at three quarters of the container limit keeps V8 able to report.
Node.js EventEmitter: once, error Events, and Listener Memory Leaks
emit is synchronous, so a throwing listener aborts the rest. An error event with no listener crashes the process, and a listener per request is the classic leak.
Node.js fs/promises: Read, Write, Watch, and Atomic File Operations
writeFile truncates before writing, so a crash leaves half a file. The atomic pattern is temp file, fsync, rename; readFile loads everything, so large files need streams.
More in Node.js
All Node.js guidesThe guides filed next to this one in Node.js, in library order.