What is the Nx enforce-module-boundaries rule and how does it work?
enforce-module-boundaries is an ESLint rule shipped with Nx's lint plugin. Each project declares string tags such as scope:orders or type:data-access in its project configuration. When the linter sees an import, the rule uses the Nx project graph to find out which project owns the imported file. It needs the graph because a path alias like @acme/orders/data-access is just a string. Once it knows the target, it compares the two projects' tags against your depConstraints.
Each constraint has a sourceTag and either onlyDependOnLibsWithTags (an allowlist) or notDependOnLibsWithTags (a denylist). A project carrying type:feature with an allowlist of type:data-access and type:util fails lint if it imports a type:feature library. The rule also does two checks that don't involve tags:
- It flags relative imports (
../../other-lib/src) that reach into another project. Those imports skip the project's public entry point and hide the dependency from the graph. - It reports circular dependencies between projects.
How a single import is evaluated:
- Source file in project A, which has tags
scope:ordersandtype:feature - Import statement:
@acme/billing/util - Project graph lookup: the import resolves to project B, which has tags
scope:billingandtype:util - Tag matching: every
depConstraintsentry whosesourceTagmatches one of A's tags is checked against B's tags - Result: the import passes if every applicable constraint allows it, and fails with a lint error if any constraint rejects it
This is a lint-time check only. It provides no build or runtime guarantee. Any code path that skips linting gets past it: a disabled rule, an unlinted file, or a runtime require of a computed path.
The rule's package name, rule name and option set have changed across Nx releases. Check the documentation for the version you run before copying configuration.
+-----------------------------+ +-----------------------------+
| Project A (source) | | depConstraints |
| tags: scope:orders | | sourceTag + allowlist: |
| type:feature | | onlyDependOnLibsWithTags |
+--------------+--------------+ | or denylist: |
| | notDependOnLibsWithTags |
v +--------------+--------------+
+-----------------------------+ |
| import '@acme/billing/util' | |
+--------------+--------------+ |
| |
v |
+-----------------------------+ |
| Project graph lookup | |
| alias -> owning project | |
+--------------+--------------+ |
| |
v |
+-----------------------------+ |
| Project B (target) | |
| tags: scope:billing | |
| type:util | |
+--------------+--------------+ |
| |
v v
+------------------------------------------------------------------+
| Tag matching: constraints whose sourceTag matches A's tags, |
| checked against B's tags |
+-----------------+--------------------------------+---------------+
v v
+-----------------------+ +-------------------------+
| PASS: all allow | | FAIL: lint error |
+-----------------------+ +-------------------------+
How enforce-module-boundaries evaluates one import: the project graph resolves the alias to its owning project, then depConstraints compare both projects' tags at lint time.
How does it work in day-to-day development?
Day to day, the rule behaves like any other ESLint rule. The workflow has four parts:
- Configuration. Tags live in each project's configuration, usually the
tagsarray inproject.json. The constraints live once, in the workspace ESLint config. Adding a project means choosing its tags. The constraint list changes only when the architecture changes. - Feedback while coding. An editor with ESLint integration shows the violation on the import line as soon as it is typed. The developer finds out before committing that the import breaks a boundary.
- Local and CI runs. Running the lint target for a project (
nx lint <project>, ornx affected -t lintfor changed projects) reports the same errors from the command line. In CI, the same command makes a violation fail the build instead of relying on a reviewer to spot it. - Graph dependency. The rule depends on the Nx project graph, which Nx computes from project configuration and source imports. A path alias that is missing from the workspace's TypeScript path mappings, or a project Nx doesn't recognise, can't be resolved correctly. In that case, fix the workspace configuration first, then re-check the violation.
When a check fails, the fix is never to edit the tags until the import passes. Move the code into a library the source is allowed to depend on, depend on a shared contract instead, or treat the change as an architecture decision and update depConstraints deliberately.
Why tag backend libraries by both scope and type?
Each tag answers a different question. scope:<domain> says which business area owns the code: scope:billing, scope:identity, or scope:shared for code any domain may use. type:<layer> says what kind of code it is, regardless of owner. The two axes are independent. A billing repository and an identity repository are both type:data-access and follow the same layering rules, but they belong to different domains and should not import each other.
| Type | May contain | Example backend projects |
|---|---|---|
type:app |
Bootstrap, wiring, deployment entry point | billing-service, identity-service |
type:feature / type:api |
HTTP or message handlers, use-case orchestration | billing-feature-invoicing, identity-api-sessions |
type:data-access |
Repositories, ORM models, external API clients | billing-data-access, identity-data-access |
type:domain |
Entities, value objects, pure business rules | billing-domain, identity-domain |
type:util |
Stateless helpers with no domain knowledge | shared-util-dates, shared-util-retry |
Give each project exactly one tag per axis. If a project carries two scope tags, it is evaluated against two sets of rules, and you can no longer tell what it may import by reading its tags. Keep the vocabulary fixed and lowercase, in the form prefix:value. A misspelled tag such as scope:biling matches no constraint, and no error points it out.
This setup pays off when several teams work across several domains. In that situation, a reviewer can easily miss one extra import in a large diff. Over a few months, those imports add up to a dependency graph nobody planned. Boundary tags turn the policy into a lint error, so the author fixes the problem before review instead of someone discovering it during a later refactor or service extraction.
Who should use scope and type boundary tags?
Scope and type tags fit teams that already run, or plan to run, several backend projects in one Nx workspace and want the dependency direction between them to stay deliberate. They are most useful in these cases:
- Multi-team backend monorepos. Several teams own different domains in one repo. Each team needs to know that other teams can't quietly depend on its internals.
- Modular monoliths with a likely split. One deployable is organised into domains that may later be extracted into separate services. Clean scope boundaries make that extraction a move instead of an untangling project.
- Codebases aiming for a layered or hexagonal design. The type axis keeps domain code free of persistence and transport concerns without anyone checking import lists by hand.
- Platform or architecture owners. These people are responsible for the overall structure but can't review every pull request.
The rule offers less to a single small service maintained by one team, to repos that don't use Nx, and to workspaces where most dependencies are dynamic or loaded through configuration, which the rule can't see. In those cases, review conventions or a lighter import rule may be enough. The trade-offs are covered in the last section.
How do you write depConstraints for layers and domains?
The rule's options take a depConstraints array. Each entry names a sourceTag and lists which tags its projects may import, usually with onlyDependOnLibsWithTags. For the layer axis, four entries are enough:
type:appmay depend ontype:feature,type:data-access,type:domainandtype:util.type:data-accessmay depend ontype:domainandtype:util.type:domainmay depend ontype:utilonly.type:utilmay depend ontype:utilonly.
The rules only allow dependencies to point inward, toward the domain. Domain code holds entities and business rules and knows nothing about databases, HTTP or message brokers. Data-access libraries implement persistence and external clients against interfaces the domain defines. This is the dependency direction of a hexagonal architecture: adapters depend on the core, and the core never depends on adapters. Utilities sit at the bottom so that anything can use them, and they import nothing above themselves.
The domain axis uses the same mechanism. Give scope:billing onlyDependOnLibsWithTags: ["scope:billing", "scope:shared"]. An allow-list is safer than adding notDependOnLibsWithTags: ["scope:identity"], because a deny-list has to be updated every time someone adds a domain, and a missed update lets the new domain through.
That leaves the question of how billing learns anything about identity. Billing should not reach into identity's libraries. Put the shared surface in a scope:shared contracts library that holds DTOs, event schemas and API types, and keep it free of behavior. At runtime, billing consumes identity's published events or calls its API. Both sides then depend on a stable contract, and neither depends on the other's internals.
// eslint.config.js (flat config) at the workspace root
const nx = require('@nx/eslint-plugin');
module.exports = [
...nx.configs['flat/base'],
{
files: ['**/*.ts'],
rules: {
'@nx/enforce-module-boundaries': ['error', {
depConstraints: [
// Layer axis: imports may only point inward, toward the domain.
{ sourceTag: 'type:app', onlyDependOnLibsWithTags: ['type:feature', 'type:data-access', 'type:domain', 'type:util'] },
// Every type tag in use needs an entry. A project whose tags match no
// sourceTag is not allowed to import any library.
{ sourceTag: 'type:feature', onlyDependOnLibsWithTags: ['type:data-access', 'type:domain', 'type:util'] },
// Adapters (DB, HTTP clients) implement interfaces owned by the domain.
{ sourceTag: 'type:data-access', onlyDependOnLibsWithTags: ['type:domain', 'type:util'] },
// The core knows nothing about adapters.
{ sourceTag: 'type:domain', onlyDependOnLibsWithTags: ['type:util'] },
{ sourceTag: 'type:util', onlyDependOnLibsWithTags: ['type:util'] },
// Scope axis: use allow-lists, not deny-lists, so new domains are blocked by default.
// Identity is reachable only through scope:shared contracts (DTOs, event schemas).
{ sourceTag: 'scope:billing', onlyDependOnLibsWithTags: ['scope:billing', 'scope:shared'] },
{ sourceTag: 'scope:identity', onlyDependOnLibsWithTags: ['scope:identity', 'scope:shared'] },
// Shared contracts must not pull in any domain.
{ sourceTag: 'scope:shared', onlyDependOnLibsWithTags: ['scope:shared'] },
],
}],
},
},
];
// Example tags in project.json: "tags": ["scope:billing", "type:domain"]
// A project must satisfy the constraints for every tag it has, on both axes.
An Nx flat ESLint config whose depConstraints enforce an inward-pointing layer order and allow-list scope rules, so billing reaches identity only through scope:shared contracts.
How do scope and type constraints combine on the same import?
Nx evaluates constraints by source project, not by import. For a given project, every depConstraints entry whose sourceTag matches one of its tags applies, and the import must satisfy all of them. A project tagged scope:billing and type:data-access therefore inherits both the billing allowlist and the data-access allowlist. The permitted dependencies are the intersection of the two.
Worked example
Take billing-data-access, tagged scope:billing and type:data-access, importing identity-domain, tagged scope:identity and type:domain. The layer rule allows type:data-access to depend on type:domain, so that check passes. The scope rule allows scope:billing to depend only on scope:billing and scope:shared, so that check fails. The linter reports an error along the lines of "A project tagged with scope:billing can only depend on libs tagged with scope:billing, scope:shared."
Don't fix this by adding scope:identity to billing's allowlist. Import the contract library described above, which is tagged scope:shared and type:domain. That import passes both rules.
Narrower and catch-all rules
Some Nx versions support allSourceTags. A rule using it applies only to projects that carry every listed tag, so you can write one rule for exactly scope:billing plus type:data-access. Check that your installed version has this option before you rely on it.
A sourceTag: '*' rule matches every project. That changes how untagged projects are handled. Without a matching rule, Nx rejects their imports. With a permissive '*' → '*' rule, an untagged project, or one whose tag is misspelled, passes every check without any warning. Adding '*' to a specific rule's allowlist has a similar effect: it switches that rule off. Keep the catch-all restrictive, or omit it.
// eslint.config.js (flat config). Verify option names against your installed Nx version.
const nx = require('@nx/eslint-plugin');
module.exports = [
...nx.configs['flat/base'],
{
files: ['**/*.ts'],
rules: {
'@nx/enforce-module-boundaries': ['error', {
depConstraints: [
// Scope axis: billing may use only billing and shared code.
{ sourceTag: 'scope:billing', onlyDependOnLibsWithTags: ['scope:billing', 'scope:shared'] },
{ sourceTag: 'scope:identity', onlyDependOnLibsWithTags: ['scope:identity', 'scope:shared'] },
{ sourceTag: 'scope:shared', onlyDependOnLibsWithTags: ['scope:shared'] },
// Layer axis: data-access may use domain, not the reverse.
{ sourceTag: 'type:data-access', onlyDependOnLibsWithTags: ['type:data-access', 'type:domain'] },
{ sourceTag: 'type:domain', onlyDependOnLibsWithTags: ['type:domain'] },
// billing-data-access matches BOTH a scope rule and a type rule,
// so an import must pass both. identity-domain (scope:identity,
// type:domain) passes the type rule but fails the scope rule.
// Narrower rule: applies only to projects carrying every listed tag.
// allSourceTags is not available in every Nx version; check yours.
{
allSourceTags: ['scope:billing', 'type:data-access'],
onlyDependOnLibsWithTags: ['type:domain', 'type:data-access'],
},
// Do NOT add this. It matches every project, so untagged or
// misspelled projects pass silently instead of being rejected:
// { sourceTag: '*', onlyDependOnLibsWithTags: ['*'] },
],
}],
},
},
];
An ESLint flat config showing scope and type constraints that both apply to billing-data-access, an optional allSourceTags rule, and the permissive '' rule to avoid.*
When should you introduce boundary tags, and how do you roll them out to an existing repo?
The best time to add tags is when a second team starts working in the repo, or when a backend grows its second domain. At that point you can still describe the intended architecture from memory. Every month you wait adds more imports to untangle.
Rolling tags out to an existing repo
- Tag every project before enforcing anything. Give each library a
scope:and atype:tag, then add a single permissive constraint that allows everything. Lint stays green, and the untagged-project gap described above is closed. - Inspect the real graph. Run
nx graphand compare it against the architecture you intend. Look for edges that point the wrong way, such as atype:data-accesslibrary importing atype:featurelibrary, or one domain reaching into another domain's internals. - Tighten one domain at a time. Replace the catch-all with real constraints for a single scope, fix what breaks, merge, and move on. This keeps each pull request reviewable.
- Block merges in CI. Run
nx affected -t linton every pull request so new violations fail the build. This only checks changed projects, so it doesn't re-lint the whole workspace. - Make tags mandatory for new libraries. Pass
--tagswhen you generate a library. Set workspace generator defaults or a review checklist so that an untagged project is caught at creation time.
What it costs
Expect the first strict rule to surface dozens of violations at once. Many of them can't be fixed by relabeling. They require moving code, splitting a library, or extracting an interface.
The tempting shortcut is to tag projects so they match today's imports. Resist it. Tags that describe the current tangle enforce nothing.
// eslint.config.mjs (workspace root)
// Rollout stage 3: 'orders' is tightened, the rest is still permissive.
import nx from '@nx/eslint-plugin';
export default [
...nx.configs['flat/base'],
{
files: ['**/*.ts'],
rules: {
'@nx/enforce-module-boundaries': [
'error',
{
depConstraints: [
// First domain moved to real rules. Orders code may only
// import orders libraries or shared libraries.
{
sourceTag: 'scope:orders',
onlyDependOnLibsWithTags: ['scope:orders', 'scope:shared'],
},
// Shared code must never reach back into a domain.
{
sourceTag: 'scope:shared',
onlyDependOnLibsWithTags: ['scope:shared'],
},
// Temporary catch-all from stage 1. It allows any edge, so it
// doesn't loosen the rules above. A project matching several
// constraints must satisfy all of them. Delete this entry once
// every scope has its own constraint.
{
sourceTag: '*',
onlyDependOnLibsWithTags: ['*'],
},
],
},
],
},
},
];
// New libraries get tags at creation time, for example:
// nx g @nx/node:library libs/orders/data-access --tags=scope:orders,type:data-access
// CI runs only on changed projects:
// nx affected -t lint
A mid-rollout ESLint flat config in which the orders and shared scopes have strict boundary rules, a temporary wildcard constraint keeps the other domains passing until they are tightened, and comments show the tagged generator command and the CI lint command.
Where do shared backend concerns like logging, config and auth belong?
Logging, configuration loading, database client setup and auth middleware are needed by almost every domain, so they belong under scope:shared. Pure helpers such as a structured logger wrapper, config schema parsing or token validation are type:util. Anything that holds a connection or talks to an external system, such as a database client factory or a secrets fetcher, is type:data-access. The type rules still apply to these libraries. A shared util cannot reach into a shared data-access library just because both carry the shared scope.
The risk is that scope:shared accepts imports from every domain, so the scope constraints stop protecting you at that point. Code lands there because it is convenient, not because it is generic. A shared library ends up holding an order-specific retry policy or a billing-flavoured auth check, and it becomes a hub that couples domains through the back door.
Three guards keep this in check:
- Clear ownership. Every shared library needs a named owning team, recorded in a CODEOWNERS file, that reviews additions to it.
- Entry criteria. Code moves into shared only when at least two domains use it and it contains no domain vocabulary.
- A path back. When only one domain still uses a shared module, or it starts encoding that domain's rules, move it back into that domain.
Treat edits to depConstraints as architecture decisions. Each change should be reviewed by the owners and come with a recorded reason. Track eslint-disable comments that target @nx/enforce-module-boundaries, for example by counting them in CI. Each one is an exception that someone agreed to, and the count should go down over time rather than grow unnoticed.
How can boundary tags save engineering time?
The time savings come from catching a boundary violation earlier, when fixing it is cheapest:
- Fixes happen while the code is fresh. A wrong import shows up as a lint error in the editor or in CI on the pull request that introduces it. The author removes one import line. Without the rule, the same edge is found months later, after other code has been built on top of it.
- Reviews get shorter. Reviewers no longer need to check every import in a large diff for direction and ownership. The lint result already covers static imports, so reviewers can spend their time on behaviour and design.
- Refactors and extractions get cheaper. If
scope:billingcan only reachscope:billingandscope:shared, the set of code to move when billing becomes its own service is known in advance. Nobody has to trace hidden dependencies before starting. - Fewer architecture discussions repeat. The constraint list records decisions that would otherwise be argued again in individual reviews. Changing it is an explicit, reviewable edit.
- CI stays proportionate.
nx affected -t lintlimits checks to changed projects, so enforcement doesn't require re-linting the whole workspace on every pull request.
Illustrative estimate (assumed inputs, not a measured result): assume a workspace where two cross-boundary imports per week would otherwise get past review. Assume each takes 15 minutes to fix when caught at lint time, and 3 hours to untangle when found later during a refactor. That gives roughly 0.5 hours a week with the rule and 6 hours a week without it, a difference of about 5.5 hours. The figure ignores the one-time rollout cost described above, which comes first. Substitute your own assumed violation rate and fix costs. If violations are rare in your repo, the savings are correspondingly small.
When should you avoid strict module boundaries, and what are the alternatives?
The rule only sees imports it can resolve statically. A require whose path is computed at runtime, a handler loaded by name from configuration, or a file excluded from the lint target never reaches the check. CI shows a clean graph while the real dependency exists anyway. Treat the rule as a strong default, not a proof.
The matrix also has a usable size. With many types and narrow domains, each new library raises a question about which constraint applies. Teams under deadline answer it with a wildcard, which removes the constraint. If you can't explain the constraint list in a few sentences, merge some tags.
Strict isolation has costs too. Banning every cross-domain import can push teams to copy a validation helper or extract a shared contract library before its shape has settled. Some coupling is legitimate, such as billing reading an order's total, and a direct, visible import is easier to review than a duplicate.
Tags govern edges, not contents. A type:domain library can still open a database connection or call an HTTP client. Layer purity inside a library needs review or a separate check.
| Approach | Enforcement strength | Setup cost | Maintenance cost |
|---|---|---|---|
| Review conventions only | Weak; depends on reviewer attention | Very low | Grows with team size |
| Generic import-restriction lint rules | Moderate; path patterns, no project graph | Low | High; patterns drift as paths move |
Nx tags with depConstraints |
Strong for static imports | Moderate | Low to moderate |
| Separate repos or packages with published interfaces | Very strong; only exported API is reachable | High | High; versioning and release overhead |
| Architecture tests | Strong, and can check library contents | Moderate to high | Moderate; tests evolve with structure |
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 nx enforce module boundaries tags, 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.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
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.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- 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.