What is an enforced module boundary in a Node.js modular monolith?
A modular monolith is a single deployable application whose code is split into modules that map to bounded contexts: billing, orders, inventory, identity. In a Node.js codebase, the typical layout gives each context one top-level folder, such as src/modules/billing and src/modules/orders. Everything a module exposes to the rest of the system goes through one public entry point, src/modules/billing/index.ts. Folders like billing/domain, billing/repositories and billing/internal are private. Other modules may import modules/billing, but never modules/billing/repositories/invoice-repo.
That is the whole boundary: a small public surface and a large private interior. It lets the billing team rename a table, split a service or change an internal type without searching the rest of the repository for callers. The alternative is a codebase where every file can import every other file.
The problem is that TypeScript and Node will resolve a deep import as happily as a public one. Nothing in the language stops a developer under deadline pressure from reaching into orders/internal to reuse a helper. Each shortcut looks harmless. After enough of them, the modules are coupled in ways no one designed or reviewed. Code review catches some of these imports, not all.
dependency-cruiser turns the boundary into executable architecture. You write the rules once as configuration. They then run against every change and fail the build when an import crosses a line.
This approach suits teams with several contributors sharing one deployable who want module independence without moving to services yet.
src/modules/ (one deployable, one repo)
+------------------------------+ +------------------------------+
| orders/ | | billing/ |
| | | |
| | allowed | +------------------------+ |
| order-service.ts --+--------+--------->| | index.ts (public) | |
| | | | +-----------+------------+ |
| | | | | |
| | | | v |
| | | denied | +------------------------+ |
| +--------+---X----->| | domain/ private | |
| | | | repositories/ private | |
| | | | internal/ private | |
| | | +------------------------+ |
+------------------------------+ +------------------------------+
| |
+--------------------+--------------------+
|
v
+-----------------------------------+
| dependency-cruiser (runs in CI) |
| allow: modules/<m>/index.ts |
| forbid: modules/<m>/<private>/** |
| violation -> build fails |
+-----------------------------------+
Code in orders may import billing only through its public index.ts, while dependency-cruiser runs in CI and fails the build on any deep import into billing's private folders.
How does dependency-cruiser enforce import rules?
dependency-cruiser never executes your code. It parses each source file, finds every import, require and dynamic import(), resolves each specifier to a real file path the way Node or your TypeScript configuration would, and builds a dependency graph. It then checks every edge in that graph against the rules in your config. Because the rules see resolved paths, an alias like @billing/internal and a relative ../../billing/internal are caught by the same rule.
Install it as a dev dependency with npm install --save-dev dependency-cruiser, then run npx depcruise --init. The init command asks a few questions about your project layout and writes .dependency-cruiser.js with a set of sensible starter rules.
Boundary rules go in the forbidden array. Each rule has four parts:
nameidentifies the rule in violation output.severityiserror,warnorinfo. Onlyerrorfails the run.commentstates the intent. Whoever hits the violation reads this, so explain why the rule exists, not just what it blocks.fromandtoare path matchers, typically regexes inpathandpathNot.
The core boundary rule uses a capture group so that a single rule covers every pair of modules:
from.pathis^src/modules/([^/]+)/to.pathis^src/modules/[^/]+/to.pathNotexcludes^src/modules/$1/and^src/modules/[^/]+/index\.ts$
The $1 in pathNot is replaced with the module name captured in from. The rule therefore allows imports within the same module and imports of another module's index file, and forbids everything else.
Next, prove the rule fires. A regex that matches nothing passes silently and looks exactly like a clean codebase. Add a file under one module that imports a non-index file from another module, then run npx depcruise src --config .dependency-cruiser.js. Confirm the run reports the violation and exits with a non-zero code, then delete the file.
// .dependency-cruiser.js (excerpt: the boundary rule only)
module.exports = {
forbidden: [
{
name: 'no-cross-module-internals',
severity: 'error', // only 'error' fails the run
comment:
'Modules talk to each other only through their public index.ts. ' +
'Importing another module\'s internals couples you to code its owners ' +
'may change freely. Export what you need from that module\'s index.ts instead.',
from: {
// Capture the importing module's name, e.g. "orders"
path: '^src/modules/([^/]+)/',
},
to: {
// Any file inside any module...
path: '^src/modules/[^/]+/',
pathNot: [
// ...except files in the same module ($1 = name captured in from.path)
'^src/modules/$1/',
// ...and except another module's public entry point
'^src/modules/[^/]+/index\\.ts$',
],
},
},
],
options: {
tsConfig: { fileName: 'tsconfig.json' }, // resolve path aliases like @billing/*
},
};
// Deliberate violation, to prove the rule fires:
// src/modules/orders/__boundary-check__.ts
// import { applyDiscount } from '../billing/internal/pricing';
//
// npx depcruise src --config .dependency-cruiser.js
// Expect one 'no-cross-module-internals' error and a non-zero exit code.
// If the run passes, the regex matches nothing: fix it before trusting a clean result.
A single forbidden rule that uses a capture group in from.path and $1 in to.pathNot to block imports of another module's non-index files for every module pair, followed by a deliberate violation that confirms the rule actually fires.
How do you configure module boundaries in TypeScript?
Path aliases are the first thing to get right. If your code imports @billing/internal/ledger and dependency-cruiser cannot resolve that alias, the dependency is recorded as unresolvable instead of as a path under src/modules/billing. Your boundary rules match resolved file paths, so the import never matches and the check passes silently. Set options.tsConfig.fileName to the same tsconfig your build uses, so paths and baseUrl resolve the same way they do for the compiler. Then keep a not-to-unresolvable rule at severity error. A broken alias setup should fail the run, not shrink what gets checked.
Type-only imports need an explicit decision. TypeScript erases import type at compile time, so dependency-cruiser only sees these imports when tsPreCompilationDeps is enabled. Set that option yourself instead of relying on a default. Then decide whether boundary rules should ignore type-only edges, for example by adding dependencyTypesNot: ["type-only"] to the rule's to block, and write a comment in the config explaining the choice.
| Choice | Benefit | Cost |
|---|---|---|
| Allow type-only imports | Low friction; sharing DTO shapes is easy | Type-level coupling grows unchecked and turns into runtime coupling later |
| Forbid type-only imports | Contracts must go through a public surface | More violations to triage; more duplicated or re-exported types |
The "index only" rule has a side effect to watch for. Teams tend to satisfy it by re-exporting everything from index.ts. Large barrel files make tree-shaking harder, slow test startup because every import loads the whole module, and can create cycles through re-exports. Keep each index small and deliberate, and pair it with a no-circular rule.
// .dependency-cruiser.js
module.exports = {
forbidden: [
{
name: 'no-cross-module-internals',
severity: 'error',
comment: 'Modules may only import other modules through their index.ts. ' +
'DECISION: type-only imports are exempt so DTO shapes can be shared; ' +
'remove dependencyTypesNot to make them violations too.',
from: { path: '^src/modules/([^/]+)/' },
to: {
path: '^src/modules/',
// $1 is the importing module: its own files and other modules' index.ts are allowed
pathNot: '^src/modules/($1/|[^/]+/index[.]ts$)',
dependencyTypesNot: ['type-only'],
},
},
{
name: 'not-to-unresolvable',
severity: 'error',
comment: 'A broken alias must fail the run, not silently skip boundary checks.',
from: {},
to: { couldNotResolve: true },
},
{
name: 'no-circular',
severity: 'error',
comment: 'Catches cycles introduced through barrel re-exports.',
from: {},
to: { circular: true },
},
],
options: {
doNotFollow: { path: 'node_modules' },
// Same tsconfig as the build, so paths/baseUrl aliases resolve identically
tsConfig: { fileName: 'tsconfig.json' },
// Set explicitly: makes import type edges visible instead of erased
tsPreCompilationDeps: true,
},
};
A dependency-cruiser config that resolves path aliases through the build's tsconfig, fails on unresolvable imports, makes the type-only import policy an explicit commented decision, and adds a no-circular rule to catch cycles through barrel files.
Which additional rules should you add early?
a no-circular rule, the first of four rules worth adding before the codebase grows.
Rules beyond the boundary
No cycles between modules. Set circular: true on a rule scoped to module roots. When billing imports orders and orders imports billing, neither can be extracted, tested, or reasoned about alone. Cycles inside one module are often tolerable. Cycles across modules are not.
Shared kernel stays pure. The shared kernel should depend on nothing from feature modules. If shared/money.ts imports from orders/internal, every module now transitively depends on orders.
No orphans. A rule with orphan: true flags files nothing imports. In a monolith these are usually dead code left after a refactor. Exclude entry points, config files, and type declarations so the rule only reports real dead code.
Restrict infrastructure access. Allow only each module's infrastructure folder to import the database client or ORM. Domain code that queries the database directly hides coupling that a later split will expose.
Give every rule a comment field that states the reason, not just the restriction. When a build fails, the comment is the first explanation a developer sees.
| Rule | What it prevents | Typical severity |
|---|---|---|
| No cross-module cycles | Modules that cannot be separated | error |
| Pure shared kernel | Hidden transitive dependencies | error |
| No orphans | Dead code accumulating | warn |
| Infrastructure restriction | Domain logic coupled to persistence | error |
For design reviews, render the graph with depcruise src --include-only "^src" --output-type dot | dot -T svg > deps.svg. The image shows coupling hotspots that are hard to see in a list of violations.
// .dependency-cruiser.js: each comment states why the rule exists
module.exports = {
forbidden: [
{
name: 'no-cross-module-cycles',
comment: 'Modules in a cycle cannot be extracted or tested alone. Break the cycle with an event or a shared-kernel type.',
severity: 'error',
from: { path: '^src/modules/([^/]+)/' },
// $1 refers to the module captured in from.path, so only cycles that leave the module are reported
to: { circular: true, pathNot: '^src/modules/$1/' },
},
{
name: 'shared-kernel-stays-pure',
comment: 'If shared code imports a feature module, every module depends on it transitively.',
severity: 'error',
from: { path: '^src/shared/' },
to: { path: '^src/modules/' },
},
{
name: 'no-orphans',
comment: 'Files nothing imports are usually dead code left after a refactor.',
severity: 'warn',
from: {
orphan: true,
// Entry points, config files and type declarations are not imported by design
pathNot: ['^src/main\\.ts$', '\\.d\\.ts$', '(^|/)[^/]+\\.config\\.(js|ts)$'],
},
to: {},
},
{
name: 'db-only-from-infrastructure',
comment: 'Only a module\'s infrastructure folder may touch the database layer, so persistence coupling stays visible.',
severity: 'error',
from: { path: '^src/modules/[^/]+/', pathNot: '^src/modules/[^/]+/infrastructure/' },
to: { path: '^src/platform/database/' },
},
],
options: {
doNotFollow: { path: 'node_modules' },
tsPreCompilationDeps: true,
},
};
A dependency-cruiser config that adds the cross-module cycle, pure shared kernel, orphan and infrastructure rules, each with a comment that explains why the rule exists.
How do you adopt boundary rules in an existing codebase and run them in CI?
Turning on strict rules in a mature codebase usually produces hundreds of violations at once. If CI fails on all of them, teams tend to disable the check instead of fixing the code. A baseline avoids that outcome. Run depcruise-baseline once to write the current violations to .dependency-cruiser-known-violations.json, commit that file, and pass --ignore-known in the check. CI then fails only on violations that are new.
A baseline that nobody owns tends to stay forever. Assign it to a named owner, review its size at a regular interval such as each sprint, and regenerate it whenever entries are fixed so that fixed violations cannot come back silently. The baseline should shrink over time and never grow.
Add an npm script such as lint:deps that cruises src with your config, and make it a required status check on the main branch. A check that is advisory gets ignored once deadlines get tight. An optional pre-commit hook gives faster feedback. To keep it quick, have it pass only the staged files, which validates their outgoing imports but can miss problems elsewhere in the graph. CI cruises the full graph, so local runs trade coverage for speed while CI provides full coverage.
Illustrative estimate (assumed inputs, not measured): Assume a team raises three boundary questions in code review each week, each takes 20 minutes, and automation settles half of them. That saves about 30 minutes per week. If setup takes about four hours, the work pays for itself in roughly eight weeks.
When should you avoid strict module boundary enforcement?
A passing check means only that the static import graph obeys your rules. Several kinds of coupling never appear in that graph:
- Dynamic loading. A
require()orimport()whose path is computed at runtime, such as a plugin name read from config, cannot be resolved statically. dependency-cruiser either skips it or reports it as unresolvable. - DI containers. When a service resolves
'billing.InvoiceRepository'by string token, the import edge points at the container, not at the billing module. - Shared data. Two modules that read and write the same database table, or depend on the same event payload shape, are coupled even though neither imports the other.
The rules can also break as the code changes. Path regexes assume a folder layout. Renaming src/modules or nesting a submodule can make a rule silently stop matching. It still passes, but it no longer protects anything.
A more serious problem is a tool that enforces the wrong boundaries. If your modules do not match how the domain actually changes, you will add exceptions every sprint. That churn means the module map is wrong. The fix is to redraw the modules, not to keep extending the allow-list.
dependency-cruiser checks import direction and reachability. It does not judge API design. A module can satisfy every rule and still export forty functions that callers treat as internals.
Finally, consider scale. A small service with a single owner already gets boundary review in every change, so the configuration and exception process may cost more than they save.
How should you handle exceptions, and what are the alternatives to dependency-cruiser?
When a rule blocks an import that looks legitimate, first decide whether the rule or the dependency is wrong. A narrowly scoped exception, such as one source path allowed to reach one target path with a comment explaining why and who owns removal, is reasonable for a migration in progress. A broad pattern that whitelists a whole module turns the rule into documentation nobody trusts.
If the need is permanent, fix the structure. Code that several modules genuinely share belongs in a shared module with its own rules. If module A needs B to react to something, B can expose an interface that A implements, or A can publish an event that B subscribes to. Both options invert the dependency, so the arrow points the way your rules say it should.
Alternatives differ mainly in how hard they are to bypass:
| Approach | Enforcement strength | Setup cost | Granularity | Runtime impact |
|---|---|---|---|---|
| Convention and code review | Weak; depends on reviewer attention | None | Whatever reviewers notice | None |
ESLint import restrictions (e.g. no-restricted-imports) |
Moderate; easy to disable inline | Low if ESLint already runs | Per import pattern; no graph-level rules like cycles | None |
| TypeScript project references or workspace packages | Strong; undeclared imports fail to resolve or build | Medium to high; build and packaging changes | Package level | None, though build orchestration changes |
| Separate services | Strongest; separated by the network | High; deployment, observability, data ownership | Service level | Network latency, partial failures |
dependency-cruiser sits between the ESLint and package options. It understands the whole graph, so it can enforce cycles and orphan rules, and it does not require restructuring your build.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to modular monolith nodejs boundaries, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.