What is the Nx enforce-module-boundaries rule and how does it work?
@nx/enforce-module-boundaries is an ESLint rule shipped in Nx's ESLint plugin. When ESLint processes a source file, the rule examines each import and resolves it against the Nx project graph, which is the workspace's model of every project and the dependencies between them. If an import resolves to a different project, usually through a workspace path alias or package name, the rule finds the tags on both the importing project and the imported project. It then checks that pair against the depConstraints you configure. If no constraint allows the dependency, lint reports an error on that import line.
The rule works at the project level. It decides whether project A may depend on project B. It does not decide how files inside a single project reference each other. If you want a project's internal folders to follow a structure, such as keeping a domain folder free of infrastructure imports, you need a separate tool or need to split those folders into separate projects.
Teams adopt the rule because it turns an architecture decision into a check that runs automatically. Without it, "feature libraries must not import from app shells" or "the billing domain must not reach into identity internals" exists only in a diagram or a wiki page. Code review becomes the only way to enforce it, and reviewers miss violations, especially in large diffs. With the rule in place, a layering violation fails lint locally and in CI, and the error points to the exact offending import.
The rule pays off most for platform and backend teams running monorepos where several teams or domains share one repository. In that setting, a dependency added casually by one team can quietly couple release cycles or leak internal APIs to everyone else.
How should you design project tags before writing constraints?
Before writing a single constraint, decide what a tag is allowed to mean. A workable scheme uses two independent axes. Every project gets exactly one layer tag (type:app, type:feature, type:domain, type:data-access, type:util) and exactly one scope tag (scope:billing, scope:identity, scope:shared). The layer says what kind of code the project holds. The scope says which domain owns it.
scope:billing scope:identity scope:shared
type:app app app
| |
type:feature feature feature
| |
type:domain domain domain ----> domain
| | |
type:data-access data-access data-access ---> data-access
| | |
type:util util util ----> util
Vertical arrows: depend downward only.
Horizontal arrows: any scope may depend on scope:shared, never on a sibling scope.
The two axes are orthogonal, so each rule covers a whole row or column and you don't have to enumerate pairs of projects. "Features may not import apps" and "billing may not import identity" are written once and apply to every project. With a flat list of ad-hoc tags, each new tag needs its own rules, and the rules can overlap or contradict one another.
| Concern | Flat ad-hoc tags | Two orthogonal axes |
|---|---|---|
| Rule count | Grows with every new tag | Fixed per axis |
| Coverage | Untagged or oddly tagged projects slip through | Every project matches one layer and one scope rule |
| Readability | billing-api-internal needs explaining |
type:domain, scope:billing explains itself |
Requiring exactly one tag per axis is what makes coverage predictable. A project with two layer tags falls under two sets of rules, and the more permissive set wins.
scope:billing scope:shared scope:identity
+-------------+ +-------------+
type:app | app | | app |
+------+------+ +------+------+
| |
v v
+-------------+ +-------------+
type:feature | feature | | feature |
+------+------+ +------+------+
| |
v v
+-------------+ +-------------+ +-------------+
type:domain | domain | --> | domain | <-- | domain |
+------+------+ +------+------+ +------+------+
| | |
v v v
+-------------+ +-------------+ +-------------+
type:data-access | data-access | --> | data-access | <-- | data-access |
+------+------+ +------+------+ +------+------+
| | |
v v v
+-------------+ +-------------+ +-------------+
type:util | util | --> | util | <-- | util |
+-------------+ +-------------+ +-------------+
Legend: | v depend downward through the layers only
--> <-- any scope may depend on scope:shared
billing and identity never depend on each other (no arrow)
Each project sits at one cell of a layer-by-scope grid: dependencies flow down the type axis and sideways only into scope:shared, so one rule per row or column covers every project.
Assigning and verifying project tags
Tags live with the project they describe. In a project that has a project.json, add them to the top-level tags array, for example "tags": ["type:domain", "scope:billing"]. For projects that Nx infers from package.json alone, put the same array under the nx key: "nx": { "tags": [...] }. Either way, the tags end up on the project node in the Nx project graph. The lint rule reads that graph. It never reads your files directly.
That indirection is why you should verify tags through Nx rather than by reading config files. A typo such as type:domian or Scope:billing is still a valid string, and tag matching is exact. The project silently falls outside every constraint written for the correct tag, and nothing fails until someone notices an import that should have been blocked.
Two commands show what the linter will see:
nx show project <name>prints the resolved project configuration, including its tags. Add--jsonto get output you can pipe into a script, for example to assert that every project has exactly onetype:tag and onescope:tag. Add--webto open the same details view in a browser.nx graphopens the interactive project graph. Selecting a project shows its tags, and filtering by tag lets you confirm that an entire layer, such as everytype:domainproject, is labeled the way you expect.
If the output doesn't reflect a recent edit, the Nx daemon may be serving a cached graph. Run nx reset and check again before you assume the configuration is wrong.
#!/usr/bin/env bash
# Verify tags from the resolved Nx project graph, which is what the lint rule reads.
# Assumes tags are set in project.json ("tags": [...]) or package.json ("nx": { "tags": [...] }).
set -euo pipefail
# Clear the daemon's cached graph so recent config edits are picked up.
nx reset
# Inspect a single project's resolved tags.
nx show project billing-domain --json | jq '.tags'
# => ["type:domain", "scope:billing"]
# Require exactly one type: tag and one scope: tag per project.
# Tag matching is exact, so a typo like "type:domian" or "Scope:billing"
# fails here instead of silently escaping every constraint.
allowed_types='^type:(app|feature|domain|util)$'
status=0
for project in $(nx show projects --json | jq -r '.[]'); do
tags=$(nx show project "$project" --json | jq -r '.tags // [] | .[]')
type_count=$(grep -cE "$allowed_types" <<<"$tags" || true)
scope_count=$(grep -cE '^scope:[a-z0-9-]+$' <<<"$tags" || true)
if [[ "$type_count" -ne 1 || "$scope_count" -ne 1 ]]; then
echo "BAD TAGS: $project -> [$(echo $tags)]"
status=1
fi
done
exit "$status"
# To check visually: open the details view in a browser, or the full graph.
# nx show project billing-domain --web
# nx graph
A script that reads each project's tags from the resolved Nx project graph using nx show project --json. It fails if any project is missing a valid type: or scope: tag, or has more than one, and nx graph and --web give the same check visually.
How do you write depConstraints for layering and scope?
Using the type:* tags from the previous section, the layering rules form a short ladder. Each entry pairs a sourceTag with onlyDependOnLibsWithTags:
type:utilmay depend only ontype:util.type:domainmay depend ontype:domainandtype:util.type:data-accessmay depend ontype:domainandtype:util.type:featuremay depend ontype:data-access,type:domainandtype:util.type:appmay depend ontype:featureand every layer below it.
Scope rules go in the same array. For example, scope:billing may depend only on scope:billing and scope:shared. A project must satisfy every constraint whose sourceTag it carries. A billing feature library is therefore checked against both the type:feature rule and the scope:billing rule. Because the rules stack this way, you never have to write a separate entry for each scope-and-layer combination.
When you need a rule for one specific combination, use allSourceTags. The entry then matches only projects that carry all of the listed tags.
For prohibitions, notDependOnLibsWithTags is clearer. "type:domain must not depend on type:infra" states the intent directly. A denylist reads better than an allowlist when the forbidden set is small and stable and the permitted set is large or keeps growing.
Add a sourceTag: '*' entry as a floor that applies to every project. Have it list your real tag vocabulary instead of '*'. That way, a dependency on an untagged or misspelled project fails instead of slipping through. A '*' target would effectively switch the rule off.
The config format differs between Nx releases. Check your installed version's docs for flat config versus legacy .eslintrc, and for how untagged projects are matched.
// eslint.config.mjs (flat config; check your Nx version's docs for the legacy .eslintrc shape)
import nx from '@nx/eslint-plugin';
export default [
...nx.configs['flat/base'],
{
files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],
rules: {
'@nx/enforce-module-boundaries': ['error', {
depConstraints: [
// Layer ladder: each layer may only reach downward.
{ sourceTag: 'type:util', onlyDependOnLibsWithTags: ['type:util'] },
{ sourceTag: 'type:domain', onlyDependOnLibsWithTags: ['type:domain', 'type:util'] },
{ sourceTag: 'type:data-access', onlyDependOnLibsWithTags: ['type:domain', 'type:util'] },
{ sourceTag: 'type:feature', onlyDependOnLibsWithTags: ['type:data-access', 'type:domain', 'type:util'] },
{ sourceTag: 'type:app', onlyDependOnLibsWithTags: ['type:feature', 'type:data-access', 'type:domain', 'type:util'] },
// Scope rule stacks on top of the layer rule a project also carries.
{ sourceTag: 'scope:billing', onlyDependOnLibsWithTags: ['scope:billing', 'scope:shared'] },
// Denylist: small, stable forbidden set; permitted set is large.
{ sourceTag: 'type:domain', notDependOnLibsWithTags: ['type:infra'] },
// Matches only projects tagged with BOTH billing and feature.
{ allSourceTags: ['scope:billing', 'type:feature'], notDependOnLibsWithTags: ['scope:shared-legacy'] },
// Floor for every project: targets must carry a real layer tag,
// so untagged or misspelled projects fail instead of slipping through.
// Do NOT list '*' here; that would accept anything.
{ sourceTag: '*', onlyDependOnLibsWithTags: ['type:app', 'type:feature', 'type:data-access', 'type:domain', 'type:util', 'type:infra'] },
],
}],
},
},
];
A flat-config @nx/enforce-module-boundaries setup that stacks layer and scope allowlists, adds denylist and allSourceTags rules, and ends with a '' floor that rejects dependencies on untagged or mistagged projects.*
What else does the rule check, and when are exemptions acceptable?
Tag constraints are only part of what the rule enforces. It also catches several structural problems that tags alone would miss.
- Relative imports across projects. An import like
../../libs/billing/src/lib/invoicereaches into another project by file path instead of through its public entry point. The rule reports it because it bypasses the project's exported API. It also hides the dependency from the project graph, so tag checks and affected-project calculations never see it. - Circular dependencies between projects. If
ordersimportspaymentsandpaymentsimportsorders, the rule reports the cycle and the projects involved. Cycles defeat layering, because neither project can be built, tested or reasoned about independently. - Static imports of lazy-loaded projects. If a project is loaded lazily somewhere through a dynamic import, a static import elsewhere pulls it into the eager bundle and silently undoes the split. The rule flags that static import.
The allow option takes a list of import paths that the rule skips entirely. It is a reasonable escape hatch for a shared test-setup path or a generated module that has no sensible tag. It is also the easiest way to quietly hollow out your architecture, because nothing ever forces anyone to remove an entry.
Treat every allow entry and every inline eslint-disable for this rule as tracked debt:
- Give each one a ticket and a named owner.
- Write the reason in a comment next to it.
- Require review on any change that adds a new one. Assigning a code owner to the ESLint config makes this straightforward.
- Periodically search the codebase for disable comments, so the count can only go down deliberately.
// eslint.config.js (repo root). Changes to this file require code-owner review.
const nx = require('@nx/eslint-plugin');
module.exports = [
...nx.configs['flat/base'],
...nx.configs['flat/typescript'],
{
files: ['**/*.ts', '**/*.tsx'],
rules: {
'@nx/enforce-module-boundaries': [
'error',
{
// Exemptions: the rule skips these import paths entirely.
// Each entry needs a ticket, an owner and a reason.
// Never add an entry without one.
allow: [
// ARCH-142 (owner: platform-team): shared Jest setup used by every
// project. It has no meaningful layer tag. Review in Q1.
'@acme/testing/setup',
// ARCH-157 (owner: api-team): generated OpenAPI client. Remove this
// entry once the generator output moves into a tagged library.
'@acme/generated/api-client',
],
depConstraints: [
{ sourceTag: 'type:app', onlyDependOnLibsWithTags: ['type:feature', 'type:data', 'type:util'] },
{ sourceTag: 'type:feature', onlyDependOnLibsWithTags: ['type:data', 'type:util'] },
{ sourceTag: 'type:data', onlyDependOnLibsWithTags: ['type:util'] },
{ sourceTag: 'type:util', onlyDependOnLibsWithTags: ['type:util'] },
],
},
],
},
},
];
// Inline disables are debt too. List them periodically so the count only drops deliberately:
// git grep -n 'eslint-disable.*@nx/enforce-module-boundaries'
An ESLint flat config for Nx in which each allow exemption sits next to its ticket, owner and reason, with a git grep command for auditing inline disable comments for the rule.
How do you enforce module boundaries in CI and roll them out to an existing codebase?
Run lint through Nx rather than calling ESLint directly. That way the rule sees the same project graph Nx uses. In pull requests, nx affected -t lint limits the run to projects touched by the change and the projects that depend on them. On the main branch, nx run-many -t lint periodically checks everything. Caching keeps both runs fast, but only if the lint target's inputs are correct. The rule's result depends on more than a project's own source files. It also depends on the tags and project configuration of the projects it imports, and on the root ESLint config. If those files are not part of the lint inputs, a retag or a new dependency can leave a stale cached "pass" in place, and the violation stays hidden until someone clears the cache.
For an existing codebase, roll out in stages:
- Start loose. Add tags everywhere with permissive constraints, so the rule runs without failing builds.
- Inventory violations. Run lint across all projects and record the current violations. This list becomes the backlog.
- Tighten one layer at a time. Begin with the layer that should have the fewest dependencies, such as
type:util. Fix or explicitly exempt its violations, then move up to the next layer. - Set a date for errors. Introduce each new constraint at warning severity, and announce when it becomes an error. Without a deadline, warnings become permanent background noise.
The payoff is in engineering time. Reviewers stop leaving "this layer shouldn't import that" comments. Contributors learn about a bad import in their editor or in CI, before review starts. Dependency cycles get blocked while they are one import deep, instead of being untangled months later across a dozen projects.
When should you avoid Nx module boundaries, and what are the alternatives?
The rule's guarantees are narrower than they look. It reasons over the project graph, so anything the graph cannot see is unchecked. That includes dynamic require calls, import paths built from strings, and generated code that wires dependencies at build time. It also says nothing about structure inside a project. A single large project can contain a tangled mix of domain logic and infrastructure, and the rule will pass it. The check runs only at lint time, so bundler configuration, dependency injection containers, and runtime plugin loading can still connect things your constraints forbid.
The costs grow as enforcement gets stricter. Fine-grained rules work best with many small projects, which means more project.json files, more tsconfig path aliases, and more jumping between folders to follow one feature. Tag schemes also drift. Renaming an axis or splitting a scope means editing every project that carries it. Strict layering can force awkward splits, such as extracting a two-function library just to satisfy a constraint. Under deadline pressure, teams may widen the allow list or apply a tag that doesn't describe the project, just to turn CI green. At that point the rule records the violation as policy instead of preventing it.
Skip it for small repos, single-team codebases, or projects so coarse that each one already spans several layers. In those cases you pay the setup and upkeep cost and get little protection in return.
| Alternative | What it enforces | Main limitation |
|---|---|---|
| Code review conventions | Whatever reviewers remember | Inconsistent, and it doesn't scale |
| Generic ESLint import restrictions | Path or pattern bans per file | No awareness of projects or tags; patterns are brittle |
| TypeScript project references | Compile-time dependency direction | Only covers TypeScript; references need manual upkeep |
| Package-level dependency declarations | Explicit, versioned dependencies | Only strict if the package manager isolates undeclared imports |
| Separate repositories | Hard physical isolation | Cross-repo changes and version coordination are slow |
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, 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.