What does nx enforce module boundaries actually check?
enforce-module-boundaries is an ESLint rule shipped with Nx's ESLint plugin. When ESLint processes a file, the rule reads each import statement, resolves the imported path to a project in the Nx project graph, and compares the importing project with the imported one. The rule has no knowledge of your architecture. It only compares the tags on those two projects against the constraints you configure.
Tags are a plain array of strings in each project's configuration, usually the tags field in project.json. Nx treats them as opaque labels. A tag like scope:billing or type:data-access means nothing special to Nx. The colon-prefixed form is a team convention, and Nx does not parse, validate or group tags by prefix. This works in your favor because you can define whatever dimensions fit your organization. It also means a typo such as scope:biling is just another valid tag, so the rule will quietly fail to match it.
The check happens only during linting. Nothing is enforced at build time, during bundling or at runtime. A forbidden import in a file that ESLint never sees, because of an ignore pattern, a skipped project or a CI job that lints only affected projects, will compile and ship without complaint. The rule protects exactly the code that your CI lint step covers.
The rule pays off most for backend and platform engineers who run monorepos where several teams own dozens of libraries. In that setup, the main risk is not a single bad import. The risk is slow, unreviewed coupling between teams that eventually makes libraries impossible to change independently.
// eslint.config.cjs at the workspace root (ESLint flat config)
// Tags are declared per project, e.g. in libs/billing/data-access/project.json:
// "tags": ["scope:billing", "type:data-access"]
// Nx treats each tag as an opaque string. A typo like "scope:biling"
// is a valid tag that no constraint below will match.
const nx = require('@nx/eslint-plugin');
module.exports = [
...nx.configs['flat/base'],
...nx.configs['flat/typescript'],
{
files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],
rules: {
'@nx/enforce-module-boundaries': [
'error',
{
depConstraints: [
// Scope axis: billing code may import only billing or shared projects.
{
sourceTag: 'scope:billing',
onlyDependOnLibsWithTags: ['scope:billing', 'scope:shared'],
},
// Type axis: data-access libs must not reach up into feature or UI libs.
{
sourceTag: 'type:data-access',
onlyDependOnLibsWithTags: ['type:data-access', 'type:util'],
},
],
},
],
},
},
];
// This is checked only when ESLint runs on a file. Files that are ignored,
// or projects your CI lint job skips, are never checked.
A flat ESLint config that turns on @nx/enforce-module-boundaries with scope: and type: constraints, which only take effect for files that ESLint actually lints.
Why use two tag axes instead of one list of rules?
Tags give each project two independent coordinates. One coordinate says who owns it: scope:orders, scope:billing, scope:shared. The other says what kind of code it is: type:app, type:feature, type:data-access, type:util. Each axis answers a different question, so each gets its own constraints.
A single list of tags runs into trouble quickly. Suppose you tag projects only by layer. Then "utils must not import data-access" is easy to write, but you have no way to say that orders must not reach into billing's data-access library. If you tag only by domain, the reverse happens: you can keep orders and billing apart, but nothing stops an orders util from pulling in an orders data-access library. To cover both rules on one axis, you end up inventing combined tags like orders-util. The number of tags then grows with domains × layers, and each new team adds a whole row of special cases.
With two axes, a project is allowed to depend on another only when both checks pass:
scope:orders scope:billing scope:shared
type:app [app] [app]
| |
type:feature [feature] [feature] [feature]
| | |
type:data-access [data] ---X--- [data] [data]
| | |
type:util [util] [util] --------> [util]
Vertical: down only (app > feature > data-access > util)
Horizontal: any scope may go to scope:shared; never sideways
This also saves review time. Questions like "can this util call the API client?" or "may orders use billing's mapper?" stop being judgment calls in pull requests. The lint rule answers them before review starts. Reviewers can then focus on behavior, and when a team really needs an exception, it shows up as a visible change to the constraint config instead of an import that slips through.
scope:orders scope:billing scope:shared
+-------------+ +-------------+
type:app | orders-app | | billing-app |
+------+------+ +------+------+
v v
+-------------+ +-------------+ +-------------+
type:feature | feature | | feature | | feature |
+------+------+ +------+------+ +------+------+
v v v
type:data- +-------------+ +-------------+ +-------------+
access | data-access |-X-| data-access | | data-access |
+------+------+ +------+------+ +------+------+
v v v
+-------------+ +-------------+ +-------------+
type:util | util | | util |-->| util |
+-------------+ +-------------+ +-------------+
v allowed: down the type axis (app > feature > data-access > util)
--> allowed: any scope -> scope:shared (shown once; applies to all)
-X- blocked: sideways between domain scopes (orders <-> billing)
blocked: any edge pointing up the type axis (e.g. util -> data)
Scope-by-type grid: a dependency is allowed only if it moves down the type axis and either stays within its own scope or targets scope:shared.
How do you write depConstraints for scope and type?
Each entry in depConstraints names a sourceTag and then restricts what projects carrying that tag may import. onlyDependOnLibsWithTags is an allow-list: the target must carry at least one of the listed tags. notDependOnLibsWithTags is a deny-list: the target must carry none of them. Allow-lists suit layered rules. Deny-lists suit narrow bans, such as keeping server-only code out of a UI library.
In the worked config, every domain scope may reach itself and scope:shared, and scope:shared may reach only itself. Types form a ladder where each layer sees itself and the layers below it:
| sourceTag | onlyDependOnLibsWithTags |
|---|---|
scope:orders |
scope:orders, scope:shared |
scope:billing |
scope:billing, scope:shared |
scope:shared |
scope:shared |
type:feature |
type:feature, type:ui, type:data-access, type:util |
type:data-access |
type:data-access, type:util |
type:util |
type:util |
When a project has several tags, every constraint whose sourceTag matches is applied, and an import must satisfy all of them. A scope:orders + type:data-access library can import scope:shared + type:util, but not scope:shared + type:feature. That conjunction is what makes the two axes independent. People who expect the first matching rule to decide the outcome are often surprised by it.
sourceTag: "*" matches every project. You can end the list with a catch-all, such as * allowed only *. Whether you do so is a trade-off. If you leave untagged projects unconstrained, they become a quiet escape hatch. If you constrain them, every new project needs tags before it can import anything useful.
// eslint.config.js (flat config). Every constraint whose sourceTag matches is applied.
const nx = require('@nx/eslint-plugin');
module.exports = [
...nx.configs['flat/base'],
{
files: ['**/*.ts', '**/*.tsx', '**/*.js'],
rules: {
'@nx/enforce-module-boundaries': ['error', {
depConstraints: [
// Scope axis: each domain sees itself plus the shared pool.
{ sourceTag: 'scope:orders', onlyDependOnLibsWithTags: ['scope:orders', 'scope:shared'] },
{ sourceTag: 'scope:billing', onlyDependOnLibsWithTags: ['scope:billing', 'scope:shared'] },
{ sourceTag: 'scope:shared', onlyDependOnLibsWithTags: ['scope:shared'] },
// Type axis: each layer sees itself and the layers below it.
{ sourceTag: 'type:feature', onlyDependOnLibsWithTags: ['type:feature', 'type:ui', 'type:data-access', 'type:util'] },
{ sourceTag: 'type:ui', onlyDependOnLibsWithTags: ['type:ui', 'type:util'] },
{ sourceTag: 'type:data-access', onlyDependOnLibsWithTags: ['type:data-access', 'type:util'] },
{ sourceTag: 'type:util', onlyDependOnLibsWithTags: ['type:util'] },
// Deny-list for a narrow ban: UI code must never pull in server-only libs.
{ sourceTag: 'type:ui', notDependOnLibsWithTags: ['platform:server'] },
// Optional catch-all: '*' matches every project. Allowing only '*' means
// any target with at least one tag is reachable, so untagged libs
// cannot be imported. Remove this entry to leave them unconstrained.
{ sourceTag: '*', onlyDependOnLibsWithTags: ['*'] },
],
}],
},
},
];
// A lib tagged ['scope:orders', 'type:data-access'] is checked against BOTH
// its scope rule and its type rule (plus '*'):
// import from ['scope:shared', 'type:util'] -> allowed (passes all)
// import from ['scope:shared', 'type:feature'] -> error (fails type rule)
// import from ['scope:billing', 'type:util'] -> error (fails scope rule)
A flat ESLint config for @nx/enforce-module-boundaries. It sets independent scope and type constraints that a multi-tagged project must satisfy together, adds a deny-list entry for a narrow ban, and ends with an optional '' catch-all.*
Which other rule options should you know about?
Beyond depConstraints, the rule accepts a few options that cover cases tag matching cannot express. Option names and exact behavior have changed across releases, so check the rule documentation for your installed Nx version before relying on any of them.
allowlists import paths that the rule skips entirely. It is useful for a shared testing utility or a generated client that every project legitimately needs. Each entry punches a hole in the graph, so record why it exists.banTransitiveDependenciesflags imports of npm packages that a project does not declare directly. Code that importslodashonly because another dependency pulls it in will break when that dependency drops or upgrades it.enforceBuildableLibDependencyflags a buildable library that imports a non-buildable one. A buildable library is compiled on its own, so it cannot inline source from a library that has no build output.bannedExternalImportssits inside a single constraint. It keeps specific npm packages out of projects with a given tag. For example,{ "sourceTag": "type:ui", "bannedExternalImports": ["pg", "aws-sdk"] }stops UI libraries from importing a database driver or a large server SDK.
| Option | Problem it solves | Main risk |
|---|---|---|
allow |
Legitimate cross-cutting imports | Exemptions accumulate and hollow out the rules |
banTransitiveDependencies |
Hidden reliance on undeclared packages | Noisy at first in workspaces with loose manifests |
enforceBuildableLibDependency |
Buildable libs that cannot build independently | Pushes teams to make many libs buildable |
bannedExternalImports |
Server-only or heavy packages leaking into the wrong layer | The deny list drifts as dependencies change |
// .eslintrc.js (fragment): confirm option names against the rule docs for your Nx version
module.exports = {
overrides: [
{
files: ['*.ts', '*.tsx', '*.js', '*.jsx'],
rules: {
'@nx/enforce-module-boundaries': [
'error',
{
// Exempt paths every project legitimately needs. Record why each one exists.
allow: ['@acme/testing-utils'],
// Flag imports of npm packages not declared in the project's own manifest
banTransitiveDependencies: true,
// Flag buildable libs that import non-buildable ones
enforceBuildableLibDependency: true,
depConstraints: [
{
sourceTag: 'type:ui',
onlyDependOnLibsWithTags: ['type:ui', 'type:util'],
// Keep the database driver and the server SDK out of UI libraries
bannedExternalImports: ['pg', 'aws-sdk'],
},
{
sourceTag: 'scope:web',
onlyDependOnLibsWithTags: ['scope:web', 'scope:shared'],
},
],
},
],
},
},
],
};
An enforce-module-boundaries configuration that combines an allow exemption, the transitive-dependency and buildable-lib checks, and a bannedExternalImports deny list on the type:ui constraint.
How do you roll module boundaries into an existing workspace?
Introduce the rule before the dependency graph gets harder to untangle. The longer a workspace grows without boundaries, the more cross-layer imports each later fix has to remove.
Step-by-step adoption
- Tag every project first. Give each project one
scope:*and onetype:*tag, plus a permissive catch-all constraint (sourceTag: "*"allowed to depend on"*"). Lint stays green, and the tags start documenting intent. - Look at the real edges. Run
nx graphand read the dependencies that already exist. You will find feature libs importing each other, apps importing apps, and utilities that pull in data access. This shows you how much work each constraint will create. - Tighten one axis at a time. Start with whichever axis causes more pain today. If teams step on each other's code, start with scope. If layering is the mess, start with type. Changing both at once produces a flood of violations that no one can triage.
- Fix or allow, never suppress per line. Move shared code into a lower-level lib, or add a narrow entry to the rule's
allowoption with a comment and an owner. Inline disable comments scatter exceptions where no one audits them. - Require both axes. A small script that reads each project configuration and fails CI when a
scope:ortype:tag is missing keeps new projects from slipping through. A review checklist can do the same job.
The up-front cost is real: tagging, moving code, and splitting libs. In return, reviewers stop policing imports by hand, and you avoid the large refactors that tangled dependencies eventually force.
When should you avoid or limit module boundary rules?
The rule runs only when ESLint runs. Generated code, files excluded by your ESLint ignore patterns, and projects without a lint target are never checked, so a violation can live there indefinitely. Check what your CI lints before trusting a green build.
Import boundaries are also not architectural boundaries. Two projects with no import between them can still be tightly coupled through a shared database schema, HTTP calls, message contracts or runtime config, and none of that is visible to the rule. Treat it as one guard among several.
Edge cases need checking in your own workspace. Dynamic imports, path aliases that do not resolve cleanly to a single project, and implicit dependencies declared in project configuration may not behave the way static imports do. Write a deliberate violation for each pattern you use and confirm the linter reports it.
| Approach | Behaviour on an untagged or new project | Adoption cost | Failure mode |
|---|---|---|---|
Allow-list (onlyDependOnLibsWithTags) |
Blocked until tagged | Higher, more initial errors | Fails closed, noisy |
Deny-list (notDependOnLibsWithTags) |
Permitted | Lower | Fails open, silent |
Tags are free text. A typo such as scope:biling raises no error. It creates a new category that no constraint covers. Allow-lists catch some of these typos, and deny-lists catch none.
Timing matters too. A taxonomy designed before the domain is understood fixes the wrong boundaries in config and in folder structure. For an early-stage or single-team repo, it is often better to wait until the seams are visible in the code.
How do you keep the tag taxonomy maintainable, and what are the alternatives?
Keep the vocabulary small and written down. A short document listing every allowed scope: and type: value, with one sentence on what each means, lets reviewers reject type:helpers when type:util already exists. Without it, tags sprawl, and each new value needs its own constraint or matches none.
Set tags when a project is created rather than afterwards. A local generator or project template that requires a scope and type means no project starts untagged, and nobody has to guess the convention.
Give the depConstraints block an owner, such as a platform team or a CODEOWNERS entry. Then a new constraint is a design decision. Without an owner, the block collects one-off exceptions until the rules no longer describe the architecture. Treat allow entries and eslint-disable comments the same way: they are debt, so keep a list of them and review it.
Watch what moves into scope:shared. Developers who relocate code there only to pass lint turn it into a catch-all that every domain depends on. That defeats the boundaries the shared layer was meant to support.
Module boundary rules are one option among several, and they can be combined:
| Approach | Enforcement point | Coverage |
|---|---|---|
| Nx module boundary rules | Lint, in editor and CI | Static imports between workspace projects |
| Separate repos or packages with published interfaces | Package publishing and versioning | Only what the package exports |
| TypeScript project references | Compiler build | Undeclared references between TS projects |
| Plain ESLint import restrictions | Lint | Path or pattern rules, no project graph |
| Architecture or contract tests | Test run | Runtime coupling, APIs and messages |
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.