• Terms of Service

Learn Internet Grow

Tech Skills

  • Learn
  • Books
  • Search
  • Create
  • Measure
  • Secure
  • Share
  • Terms of Service

CommonJS vs ESM: The Interop Nobody Has Finished Yet

Filed Under: Search

Something in node_modules throws ERR_REQUIRE_ASYNC_MODULE, and the CommonJS vs ESM question stops being a style debate. You did not change anything. A transitive dependency shipped a minor version that added one await at the top of a file, and your require() call is now structurally incapable of loading it. No flag fixes this. No bundler setting fixes it either, if the bundler is honest.

A stone bridge built inward from both banks, one span pre-cut to a glowing surveyed line and the other improvised course by course, meeting at a mismatched seam packed with shims.

The reason is not stubbornness, not bad management, and not a feature anyone forgot to implement. The two systems make incompatible promises about when a program is allowed to know what a module exports, and every rough edge in the interop layer is that one disagreement surfacing somewhere new. ES modules were standardised in the 6th edition of ECMA-262 in June 2015. More than ten years later, the bridge is still being built in public, one Node release at a time.

require Returns the Exported API. That One Sentence Decided Everything.

The CommonJS module specification is still online, at wiki.commonjs.org/wiki/Modules/1.1. Its footer says the page was last modified on 20 November 2014; its status line still reads STATUS: MULTIPLE IMPLEMENTATIONS. The whole contract for the module system that roughly half the npm registry still ships in fits on two screens, and it opens like this:

In a module, there is a free variable “require”, that is a Function.

1. The “require” function accepts a module identifier.

2. “require” returns the exported API of the foreign module.

A function call that returns the module. That is the entire commitment, and everything follows from it mechanically. A function that returns a value cannot wait — not for a network fetch, an incomplete disk read, or a promise. It must have the answer by the time it returns, so the module it loads must already have finished executing, so require runs that dependency right there, in the middle of your file, before your next line.

Two things about that document are worth checking rather than taking on trust. Fetched and string-matched on 2026-09-09, script, style and inline SVG stripped first: the words synchronous and asynchronous appear zero times on the page, and so does Node. The specification everybody calls “the synchronous module system” never uses the word, and never mentions the runtime that made it universal. The synchrony is nowhere declared — it is an unavoidable consequence of the API’s shape.

An open brass service hatch with a wrapped parcel already resting on its shelf, backed by a shallow brick recess that ends in a solid wall a few feet behind.

The spec is candid about a second consequence, in the clause most people never read:

If there is a dependency cycle, the foreign module may not have finished executing at the time it is required by one of its transitive dependencies; in this case, the object returned by “require” must contain at least the exports that the foreign module has prepared before the call to require that led to the current module’s execution.

Read that carefully: CommonJS formally permits require to hand you a half-built object. Not as a bug — as the specified behaviour. That is what “answers at runtime” costs. The spec also declines to say how a module identifier becomes a file: under a heading called Unspecified, it lists “Whether a PATH is supported by the module loader” among the “important points of interoperability” it leaves open. Node filled that hole with the node_modules directory walk, and that invention, not the specification, is what the ecosystem standardised on.

Node’s docs show the mechanism in one line. Under “The module wrapper”, modules.html states that “Before a module’s code is executed, Node.js will wrap it with a function wrapper that looks like the following”, and prints it:

(function(exports, require, module, __filename, __dirname) {// Module code actually lives in here});

A CommonJS module is a function body, and require is one of its parameters. You can shadow it, reassign it, call it inside an if, build its argument by string concatenation, or hand it to another function. Nothing outside the running program can know what a CommonJS file exports without executing it, because “what it exports” is whatever module.exports happens to point at when the function returns.

Load, Link, Evaluate — and Only Then Run a Line

ECMA-262 answers the same question in a completely different order. Section 16.2.1.5, “Abstract Module Records”, in the published ES2026 edition, defines three abstract methods that run in a fixed sequence. The wording of each is the argument in miniature.

LoadRequestedModules — “The abstract method LoadRequestedModules takes optional argument hostDefined (anything) and returns a Promise.” Its purpose: “It prepares the module for linking by recursively loading all its dependencies.”

Link — “It prepares the module for evaluation by transitively resolving all module dependencies and creating a Module Environment Record.” And then the constraint: “LoadRequestedModules must have completed successfully prior to invoking this method.”

Evaluate — the phase that finally runs your code. “Link must have completed successfully prior to invoking this method.”

The whole graph is fetched, every import in it is bound to a specific export in a specific module, and only then does the first statement execute. ResolveExport, which performs that binding, carries a guarantee CommonJS structurally cannot offer: “Each time this operation is called with a specific exportName, resolveSet pair as arguments it must return the same result.”

That is what “statically analysable” buys. Tree-shaking works because a bundler can prove which bindings are never resolved. Importing a name that does not exist fails before your program starts, rather than as an undefined three hours into a job. Neither is available where the export list is a runtime value.

An unlit chandelier whose every arm and filament is already wired and seated, with one warm conductor running from an unthrown switch to its central trunk and unused glass tubes set aside on the floor.

And note what returns a Promise: the very first phase. Asynchrony is in the standard’s module machinery before any user code runs, and a require() call that must return a value cannot participate in a process whose opening move is a promise. That is not an implementation gap in Node. It is arithmetic.

One absence explains why this is Node’s problem and not TC39’s. Fetched on 2026-09-09 and searched with script, style and SVG blocks removed first, the 7.5 MB ES2026 specification contains zero occurrences of the string CommonJS, and exactly one of Node.js — in a note about the scheduling priority of promise-handling Jobs, nowhere near the modules clause. The standard that defines ES modules has never acknowledged the system it displaced. Interop was never in the committee’s scope; it was left to the hosts, and Node is the host with the most to lose.

The Two Systems, Side by Side

CommonJSES modulesWhat this actually breaks
When dependencies resolveAt runtime, when the require() line executesBefore evaluation, in LoadRequestedModules then LinkA conditional require() has no ESM equivalent except import(), which is async
What an export list isWhatever module.exports holds when the function returnsA static list fixed at parse timeNamed imports from a CJS package are a guess, and the guess sometimes misses
TimingSynchronous, as a consequence of returning a valueAsynchronous by construction, from the first phaserequire() of a module using top-level await throws, and always will
Cyclic dependenciesMay return a partially populated object, by specificationBindings are linked first; live bindings fill in during evaluationA cycle that “worked” in CJS can surface as an access error after conversion
Tree-shakingNot soundly possibleThe point of static analysisBundle size, and dead code you cannot prove is dead
Filename and directory__filename, __dirname as wrapper parametersimport.meta.filename, import.meta.dirnameCopy-pasted path helpers throw ReferenceError on line one
Resolution rulesExtension search, folders as modules, node_modules walkNo extension search, no directory indexes, URLs supportedimport './utils' fails where require('./utils') succeeded
Node stability, Sept 2026Stability: 2 - StableStability: 2 - StableBoth are stable. The bridge between them is not.

The Date on require(esm) Is Not the Date You Were Told

Node’s modules.html carries a version history on “Loading ECMAScript modules using require()“. Read from the v26 documentation on 2026-09-09: added in v22.0.0 (24 April 2024) and v20.17.0; out from behind --experimental-require-module in v22.12.0 (2 December 2024); stopped emitting a warning by default in v22.13.0 (6 January 2025); and then, against version v25.4.0, a Changes entry of one sentence with no elaboration:

This feature is no longer experimental.

v25.4.0 was released on 19 January 2026 — ten years and seven months after ES modules were standardised. That is the number usually quoted, and on its own it misleads in a way that matters if you run the servers. Node’s release table, loaded the same day, lists v25 as EOL: an odd-numbered line, first released 15 October 2025, last updated 31 March 2026, which never became LTS. The page’s own guidance is unambiguous: “Production applications should only use Active LTS or Maintenance LTS releases.”

So the honest version needs the backport. Checked against the per-line documentation on 2026-09-09:

  • v24 “Krypton” (LTS) — the top history row is v24.15.0, carrying that identical sentence. v24.15.0 shipped 15 April 2026. The section has no stability banner at all.
  • v22 “Jod” (LTS) — the same section still carries Stability: 1.2 - Release candidate, and its history stops at v22.13.0.

On the LTS line a great many production systems still run, require(esm) is documented as a release candidate. When someone tells you it is stable now, the follow-up is which major line you are on. The first supportable release in which Node’s own documentation calls it non-experimental is v24.15.0, April 2026 — not v25.4.0.

Top-Level await Is Not an Excluded Feature. It Is the Contradiction, Made Visible.

The requirement list for require(esm) opens with a condition stated as a permanent property, not a current limitation:

The module is fully synchronous (contains no top-level await); and

And the failure is named: “If the module being require()‘d contains top-level await, or the module graph it imports contains top-level await, ERR_REQUIRE_ASYNC_MODULE will be thrown. In this case, users should load the asynchronous module using import().”

Two overlapping circular vault doors in one bulkhead whose rings of locking pins drift out of phase, so that at the overlap one pin drives into solid steel instead of a socket.

This is the one paragraph worth carrying away from the whole subject. It is easy to read that exclusion as a gap someone will close in a future release. It is not. The specification has a field for exactly this. Section 16.2.1.6, “Cyclic Module Records”, gives every module a slot called [[HasTLA]]: “Whether this module is individually asynchronous (for example, if it’s a Source Text Module Record containing a top-level await). Having an asynchronous dependency does not mean this field is true. This field must not change after the module is parsed.”

A module marked [[HasTLA]] finishes evaluating on a later turn of the event loop. require() must return a value on this one. No engineering reconciles those two facts, and Node is right to word the exclusion as a requirement rather than a roadmap item. Note the transitivity too: any dependency of any dependency using top-level await poisons the whole require() path, which is why the failure so often appears after a patch bump in something you have never opened.

Node exposes the same line as a package-level declaration: the "module-sync" export condition in packages.html is for ES modules “that does not contain top-level await in its module graph – if it does, ERR_REQUIRE_ASYNC_MODULE will be thrown when the module is require()-ed.” An author promising, in package.json, that a whole subtree stays on the synchronous side — a promise the runtime cannot check until it tries.

Going the Other Way, Node Guesses — and Says So

Importing CommonJS from ESM has the opposite problem, and Node’s esm.html documents it with unusual candour. The ES module namespace has to exist before the imported module runs — that is what Link means — but a CommonJS module’s exports do not exist until it has run. Node’s own wording:

In addition, a heuristic static analysis is performed against the source text of the CommonJS module to get a best-effort static list of exports to provide on the namespace from values on module.exports. This is necessary since these namespaces must be constructed prior to the evaluation of the CJS module.

“Heuristic static analysis” against “source text” is parsing a file to guess what running it would have done. Two sentences later the page states the limits without hedging:

Live binding updates or new exports added to module.exports are not detected for these named exports.

The detection of named exports is based on common syntax patterns but does not always correctly detect named exports. In these cases, using the default import form described above can be a better option.

A draped sculpture beside a brass wire armature copied from its silhouette, matching everywhere except one low projection the armature replaces with a confident unbroken curve.

That is the whole reason import { readFile } from 'some-cjs-package' sometimes throws SyntaxError: The requested module does not provide an export named 'readFile' while import pkg from 'some-cjs-package'; const { readFile } = pkg; works perfectly. Nothing is broken in the package; the parser could not see through the pattern its author used. And the parser itself has changed under everyone: the v18, v20 and v22 documentation sends you to cjs-module-lexer for “the exact semantics implemented”, pinned at tree/1.2.2 on v18 and tree/2.0.0 on v20 and v22 — while the v24 and v26 documentation sends you to merve, a C++ lexer, instead. Checked across all four lines on 2026-09-09. Which named exports resolve is a property of a library version, not of the language.

The reverse direction has its own tax: “The result returned by require() is the module namespace object, which places the default export in the .default property.” That is the origin of every require('esm-package').default — not a workaround someone invented, but the documented shape of the bridge.

The Documentation for the Hardest Case Is a Link

"type": "module" in package.json makes every .js file under it an ES module. .mjs and .cjs override it absolutely — “Regardless of the value of the "type" field, .mjs files are always treated as ES modules and .cjs files are always treated as CommonJS.” Conditional exports lets one package present a different entry point to require and to import. Those three mechanisms are how dual publishing works, and each is documented well.

What they produce together is not. Node’s conditional-exports documentation warns that “Using the "import" and "require" conditions can lead to some hazards, which are further explained in the dual CommonJS/ES module packages section” — and links to it. Loaded 2026-09-09, that section of packages.html reads, in its entirety:

See the package examples repository for details.

One sentence, pointing at github.com/nodejs/package-examples. The official reference for the hardest problem in the subject is a pointer somewhere else, and the page that sends you there is the same page that raised the alarm.

The guidance was not simply never written. It was written and then removed. Node 18’s packages.html — still served, checked 2026-09-09 — carries the full treatment: a “Dual package hazard” section, a “Writing dual packages while avoiding or minimizing hazards” section, and two named strategies, “Approach #1: Use an ES module wrapper” and “Approach #2: Isolate state”. The v20 docs have none of them, and neither do v22, v24 or v26. The current esm.html still carries the empty anchor stubs — esm_dual_package_hazard, esm_approach_1_use_an_es_module_wrapper, esm_approach_2_isolate_state — so old links keep resolving to the place where the text used to be.

Node 18’s definition remains the clearest statement of what you are risking:

When an application is using a package that provides both CommonJS and ES module sources, there is a risk of certain bugs if both versions of the package get loaded. This potential comes from the fact that the pkgInstance created by const pkgInstance = require('pkg') is not the same as the pkgInstance created by import pkgInstance from 'pkg' (or an alternative main path like 'pkg/module'). This is the “dual package hazard,” where two versions of the same package can be loaded within the same runtime environment.

And the symptom, same document: “If the package main export is a constructor, an instanceof comparison of instances created by the two versions returns false, and if the export is an object, properties added to one (like pkgInstance.foo = 3) are not present on the other.” Two copies of your logger, two registries, two caches, one process — and instanceof telling you, correctly, that the thing is not the thing.

One symmetrical room with two identical desks and ledgers facing each other across a glass pane that reads as a mirror from both sides, the two ledgers' ribbons resting at different depths.

One more current-state detail belongs here. When a .js file has no controlling "type" field, Node inspects the source, and the fallback is as expensive as it sounds:

In other words, Node.js tries to run such “ambiguous” files as CommonJS first, and will retry evaluating them as ES modules if the evaluation as CommonJS fails because the parser found ES module syntax.

The same page notes that this “incurs a performance cost”. The mechanism is called syntax detection, and its stability label — identical in the v22, v24 and v26 documentation on 2026-09-09 — is Stability: 1.2 - Release candidate. The thing that decides what your file is has been a release candidate across three major lines.

A Module System Is a Promise About When You Can Know Things

Strip the syntax away and this stops being a JavaScript story.

CommonJS promises answers at runtime: ask, and the answer is computed then, from whatever state the program is in. ESM promises answers before execution: everything knowable is fixed while nothing is running. Each buys something real. Runtime resolution buys conditional loading, monkey-patching, plugin systems that discover their own extensions, and a module identifier you can build from a string. Pre-execution resolution buys tree-shaking, name checking, cycle handling that does not depend on statement order, and tools that can reason about a program without running it.

You cannot hold both promises at once, and any bridge between them has to break one. require(esm) breaks ESM’s asynchrony guarantee, and pays by refusing the modules where that guarantee is load-bearing. Importing CJS from ESM breaks CommonJS’s runtime freedom, and pays with a parser that guesses. Neither is a bad implementation. They are the only two shapes available.

Two mosaic floors meeting along a diagonal seam — one laid over a drawn plan visible through the grout, the other grown outward from a point — with every split and doubled tile confined to the narrow join.

If that feels familiar, it should: it is the trade behind static versus dynamic dispatch, early versus late binding, a schema versus a document store. The interesting question is never which is better — it is that the boundary between two systems making different when-do-you-know promises is always where complexity accumulates, and it accumulates on whoever owns the boundary. In JavaScript that is Node, alone, because the language standard never mentioned the problem. It is also why both of Node’s challengers concluded npm compatibility was non-negotiable rather than something a clean-sheet runtime could design away.

The practical advice, as of September 2026: publish ESM-only if your dependents can take it and CommonJS-only if they cannot, because dual publishing is where the hazard lives. Set "type" explicitly, even in an all-CommonJS package. Treat top-level await in a library as a decision to be ESM-only forever, because it is one. And when the error arrives, read the version-history table in Node’s own documentation rather than a blog post, this one included — it moves every few months, and it is dated.

❓ Frequently Asked Questions

Is require() of an ES module stable in 2026, or not? It depends which Node line you are on, which is why the answer circulates in both forms. As of 9 September 2026: the v26 docs mark it “no longer experimental” from v25.4.0 (19 January 2026), a line that is now EOL; the v24 “Krypton” LTS docs record the backport as v24.15.0 (15 April 2026), with no stability banner; the v22 “Jod” LTS docs still show Stability: 1.2 - Release candidate. Check process.version before deciding.

Why can’t require() ever load a module that uses top-level await? Because require() returns the module as the value of a function call, on the current turn of the event loop, and a module with top-level await finishes evaluating on a later one. ECMA-262 marks such modules with [[HasTLA]], a field that “must not change after the module is parsed”. It is a contradiction, not a missing feature, and it applies transitively across the whole imported graph.

Why does import { thing } from 'a-cjs-package' fail when the package clearly exports thing? Node builds the ES module namespace before the CommonJS file runs, so it cannot observe the exports; it parses the source and guesses. Node’s documentation says the detection “is based on common syntax patterns but does not always correctly detect named exports”. Use the default import and destructure: import pkg from 'a-cjs-package'; const { thing } = pkg;.

What is the dual package hazard, in one sentence? If a package ships both builds and both load in one process — usually because your app imports one and a dependency requires the other — you get two separate instances, so instanceof returns false across them and state written to one is invisible to the other.

Do I need .mjs and .cjs if I am already setting "type"? Not usually. "type" governs every .js file under it. The extensions exist for the exceptions: .mjs is always an ES module and .cjs always CommonJS regardless of "type", which makes them the reliable way to put one file of the other kind inside a package.

Is a bundler a way out of this? It moves the problem rather than removing it. A bundler still has to decide what a CommonJS file exports without running it — same analysis, same failure modes — and it still has to pick one build of a dual package, which is one of the ways the hazard gets created. It hides the symptoms in development, which is why the failure often first appears in production.


📦 Recommended Resources

Some links below are Amazon affiliate links. If you buy through them this site earns a small commission at no extra cost to you.

Start with the free primaries, because on this subject they genuinely beat every book. Three documents settle almost every argument you will have about this: Node’s modules.html and esm.html — read the version-history tables, not just the prose, because the dates are the story — and packages.html for "type", conditional exports and the resolution rules. Then §16.2 of the published ES2026 specification, which is shorter and far more readable than its reputation; the LoadRequestedModules / Link / Evaluate table in §16.2.1.5 is two paragraphs and explains more than most blog posts. For dual publishing specifically, github.com/nodejs/package-examples is where Node’s own documentation now sends you, and the two-page CommonJS Modules/1.1 spec is worth reading once for how little it actually says. All free. The books below are for the layer underneath.

  1. JavaScript: The Definitive Guide by David Flanagan (O’Reilly, 7th edition, 2020) — the reference that treats modules as a language feature rather than a build-tool concern. Its modules chapter walks through the ad-hoc closure patterns that came before CommonJS, then CommonJS, then ES modules, which is the right order for understanding why each one exists. Flanagan is unusually careful about specification-level behaviour, so it is a good companion to reading ECMA-262 directly rather than a substitute for it. Predates require(esm) and the current interop work by several years — use it for the model, and Node’s docs for the current state.
  1. Node.js Design Patterns by Mario Casciaro and Luciano Mammino (Packt, 3rd edition, 2020) — the second chapter is devoted to the module system, and it is the best book-length treatment of the specific gap this article is about: the module wrapper, why module.exports behaves the way it does under cycles, and what changes when the same code is loaded as ESM. The rest of the book is patterns for large Node codebases, which is where dual-package problems actually bite. Same caveat on age; the mechanics it explains have not changed, the stability labels have.
  1. A Philosophy of Software Design by John Ousterhout (Yaknyam Press, 2018) — not a JavaScript book, and it is here for the last section of this article. Ousterhout’s core argument is about where complexity accumulates in a system: at interfaces, and specifically at interfaces that leak the assumptions of what is behind them. The CommonJS/ESM boundary is a textbook case — two subsystems with incompatible guarantees about when information is available, and every cost landing on whoever owns the seam. Short, opinionated, and it will change how you read the trade-off rather than just how you configure it.

✅ Pro tip: Before reaching for a bundler config, run node --print "require('./the-package')" and then node --input-type=module --eval "import('./the-package').then(m => console.log(Object.keys(m)))" against the dependency that broke. The first tells you whether the synchronous path works at all; the second shows you exactly which named exports Node’s static analysis managed to find. Most interop bugs are visible in those two lines, and the difference between them is the whole article.

Newsletter

Tags

Agentic AI Agentic Development AI AI Agents AI Coding Agents Blockchain Bounded Context Browser ChatGPT Plugins Claude Code CLPR Context Engineering Cryptocurrency DePin Developer Tools Distributed Systems DLT Domain-Driven Design Google Search HBAR Hedera Home Networking Internet Internet Performance LLM Machine Learning MCP Model Context Protocol Network Architecture Network Diagnostics Network Security News NLP Postgres PostgreSQL Productivity RAG Routers Saga Pattern SEO Software Architecture software engineering Troubleshooting Twitter Web3

Recent Articles

  • AI Agent Memory: Search and RAG Limits November 6, 2026
  • Plan Locally, Execute in the Cloud: Claude Code’s Own Recommended Workflow November 6, 2026
  • The AI Evaluation Scorer That Never Read a Transcript November 6, 2026
  • What Is a Browser Engine? Blink & V8 Explained November 5, 2026
  • Why Postgres Is Winning: The $1B Acquisition Wave November 5, 2026
  • RENDER Tokenomics Explained: Burn, Mint, Repeat November 5, 2026

Copyright © 2026 · News Pro Theme On Genesis Framework · WordPress · Log in

Content on this site is produced with the assistance of Large Language Models and edited by a human. It is intended for educational purposes — facts may occasionally be incorrect. If you spot an error, please email Larionovdmitri@learninternetgrow.com.

Affiliate Disclosure: This site contains affiliate links to Amazon and other partners. If you purchase through these links, LearnInternetGrow.com may earn a commission at no additional cost to you. We only recommend products we genuinely believe in.

Privacy Policy · Terms of Service