AceDevHub
Intermediate Node.js Interview QuestionsIntermediateConcept

Node.js · Question 39

What are circular dependencies in Node.js and how do you handle them?

Direct answer

Circular deps occur when module A requires B while B requires A — Node returns partially initialized exports from cache; fix by restructuring layers, lazy require inside functions, or dependency injection instead of mutual top-level imports.

Because modules are cached during load (Q36), a circular graph does not infinite-loop — but one side may read undefined exports if it accesses bindings before the other module finishes executing.

Why interviewers ask

  1. Load order — A starts, requires B; B requires A; A's exports object exists but properties may be unset.
  2. Symptoms — TypeError: X is not a function, undefined handler at startup.
  3. Fix: restructure — extract shared types/utils to a third module both depend on.
  4. Fix: lazy load — require('./b') inside a function after all modules initialized.
circular-fix.cjs
// a.cjs
exports.name = "A";
const b = require("./b.cjs"); // b may see partial a

// Better: shared.cjs holds interfaces
// a.cjs and b.cjs both require('./shared.cjs') only

// Lazy pattern in a.cjs
function getB() {
  return require("./b.cjs");
}
module.exports = { name: "A", getB };