skip to content

A Node.js service logs "Accessing non-existent property 'query' of module exports inside circular dependency" and later fails with query is not a function; what is happening, and how do you fix it?

level: seniorimportance: should knowfreq 35%

answer

  1. cached before it finishes running
  2. unfinished module.exports handed out
  3. warning proxy on plain objects
  4. replacing module.exports abandons callers
  5. --trace-warnings finds the read

basics

~20 s

Two CommonJS files require each other, so one received the other's unfinished module.exports and read query before it existed. Break the cycle, or keep the object and read the property at call time without replacing module.exports.

solid answer

~40 s

Node caches a CommonJS module before running it, so a `require` that loops back returns the module's **unfinished** `module.exports`. When that is a plain object, Node gives it a temporary prototype that emits this warning when code reads a missing property, and the read returns `undefined`. It stays broken in two cases: destructuring at require time (`const { query } = require('./db')`) copies `undefined` for good, and a module that ends with `module.exports = { query }` leaves its cycle partner holding the abandoned original object. Run with `--trace-warnings` to find the line that read it. Fix by moving shared code into a third module, or by adding properties to `exports` and reading `db.query` at call time, or by requiring inside the function that needs it.

code

javascript · 26 lines
javascript
// db.js
const audit = require('./audit.js'); // audit.js requires db.js back

exports.query = function query(sql) {
  audit.record(sql);
  return [];
};

// audit.js
const { query } = require('./db.js'); // read while db.js is unfinished

exports.record = function record(sql) {
  console.log('audit:', sql);
};

exports.purge = function purge() {
  return query('DELETE FROM sessions');
};

// main.js
require('./db.js');
try {
  require('./audit.js').purge();
} catch (err) {
  console.log(err.message); // query is not a function
}

go deeper

for a junior

Recall that when two CommonJS files require each other, one of them can receive the other's exports before they are filled in.

for a middle

Explain that Node caches a module before running it, so a looping require returns the unfinished module.exports object instead of throwing.

for a senior

Diagnose from the warning text, use --trace-warnings to find the read, and explain why destructuring or replacing module.exports turns a timing issue into a permanent bug.

for a principal

Decide whether the codebase should forbid module cycles through tooling, since every cycle carries load-order risk that reviewers rarely catch by reading.

## The symptom A service starts, mostly works, and then one code path fails with `TypeError: query is not a function`. Earlier in stderr there is a line like: ```plaintext (node:4127) Warning: Accessing non-existent property 'query' of module exports inside circular dependency (Use `node --trace-warnings ...` to show where the warning was created) ``` Both lines come from one cause: two CommonJS files require each other, and one of them read a property from the other's exports **before that property existed**. ## How Node produces a partial exports object Node's CommonJS loader stores a module in `require.cache` **before** running its code. With `db.js` and `audit.js` requiring each other: 1. `main.js` requires `db.js`. Node caches it and starts running it. 2. The first line of `db.js` requires `audit.js`. Node caches and starts running `audit.js`. 3. `audit.js` requires `db.js`. It is already in the cache, still unfinished, so Node returns its **current `module.exports`**, which is still empty. 4. `audit.js` finishes; control returns to `db.js`, which then defines `query`. Nothing throws at step 3, which is what makes cycles slow to find: Node deliberately returns the unfinished object so loading can complete. The Node documentation explains that handing out the unfinished exports is what prevents an infinite loop, and warns that cyclic dependencies need careful planning. Which file sees the partial object depends on which one is required first, so the same pair of files can behave differently from two entry points. ## What the warning is When the unfinished exports object is a **plain object**, Node temporarily swaps its prototype for an internal proxy. Reading a property the object does not have then calls `process.emitWarning` with the message above and returns `undefined`. When the module finishes loading and its `module.exports` is still that same object, Node restores the ordinary prototype. Three details matter in practice: - **The warning is emitted asynchronously**, so it may print after the error it explains. Read it as a clue, not as a timeline. - **`--trace-warnings`** prints the warning with a stack trace, pointing at the exact line that read the missing property. - **Exports that are not plain objects get no warning**: if the cycle hands out a function, a class instance or transpiled output marked `__esModule`, a missing property is just `undefined`, silently. ## The two patterns that make it permanent A partial object is harmless if the property is read *later*, after both files finished. It becomes a bug in two cases: | Pattern | Why it stays broken | |---|---| | Destructuring at require time: `const { query } = require('./db')` | The value is copied while it is still `undefined` and is never updated | | The other file replaces its exports at the end: `module.exports = { query }` | The early caller holds the original object, which never receives the new properties | The second pattern is subtle. Adding properties with `exports.query = ...` or `module.exports.query = ...` mutates the object the early caller already holds, so the property appears there once `db.js` finishes. Replacing `module.exports` creates a new object that only later callers see; the cycle partner keeps the abandoned one for the life of the process, and reads on it keep producing this warning. ## Fixing it In order of preference: 1. **Break the cycle.** Move the code both files need into a third module that neither of them requires back. This is the only fix that removes the hazard instead of managing it. 2. **Keep the object and read late.** In the module that receives the partial exports, keep a reference (`const db = require('./db')`) and read `db.query` inside the function that needs it, at call time. In the other module, add properties to `exports` rather than replacing `module.exports`. 3. **Require lazily.** Move the `require` call inside the function that needs it, so it runs after both files have loaded. This works, but hides a dependency inside a function body. To confirm the cycle, run with `--trace-warnings` to find the reading line, then follow the `require` calls from that file back to itself. Teams that hit this repeatedly usually add a lint rule or a dependency-graph check that rejects import cycles in CI, which is cheaper than finding each one at run time. The general language-level picture of circular imports, and how ES modules handle them with live bindings, is covered in the JavaScript material on circular dependencies; what is specific here is Node's partial `module.exports`, its warning proxy, and how replacing `module.exports` turns a timing problem into a permanent one.

  • In Node.js, why can a CommonJS cycle fail with no circular-dependency warning at all?
    Node installs the warning prototype only when the unfinished `module.exports` is a plain object that is not marked `__esModule`. If the module set `module.exports` to a function or class instance before the cycle reached it, or the file is transpiled output with the `__esModule` marker, a missing property simply reads as `undefined` with no warning, so the first sign is the later `TypeError`.
  • In Node.js, why does requiring inside the function that needs the module avoid the partial exports?
    A `require` inside a function runs when the function is called, normally after every module in the cycle has finished loading. By then the cache entry holds the completed `module.exports`, so the caller gets real properties. The cost is a hidden dependency and a cache lookup per call, so breaking the cycle is still the cleaner fix.

  • Node throws an error as soon as two CommonJS files require each other
  • Destructured CommonJS imports update once the other module finishes loading
  • Replacing module.exports at the end of a file is safe inside a cycle
  • The circular-dependency warning prints for every missing property in any cycle
  • --no-warnings fixes the problem by removing the warning