What does nx enforce-module-boundaries actually check?

enforce-module-boundaries is an ESLint rule shipped with Nx's ESLint plugin. When it lints a file, it resolves each import to a project in the Nx project graph, which Nx builds from your workspace configuration and source analysis. The rule then checks the edge between the importing project and the imported one. It looks at imports between projects. It does not look at how code is organized inside a single project.

Even before you add any tags, the rule catches two structural problems.

  • Reaching past a project's public entry point. If code in one project imports another project through a relative path that climbs out of its own folder, or through a deep path into the other project's source files, the rule flags it. Consumers are expected to go through the published alias, which maps to the library's index file. Deep imports bind a consumer to internal files the owning team never agreed to support, so a routine refactor in one library can break another team's build.
  • Circular dependencies between projects. If library A imports B and B imports A, directly or through a longer chain, the rule reports the cycle. Cycles make build order ambiguous, weaken caching and affected-project calculations, and usually signal that two libraries should be merged or split differently.

Teams adopt the rule because it turns architecture diagrams into a contract the linter checks. "Payments code must not import from the admin UI" becomes a lint error rather than a review comment that someone might miss. Platform and backend engineers who run monorepos shared by several teams get the most out of it, because drift across team boundaries is hard to spot by reading code.

The rule's name, package scope and options have changed across Nx releases. Check the documentation for the version installed in your workspace.

// apps/billing-api/src/invoices/create-invoice.ts
// Lives in the 'billing-api' project and depends on the 'payments-core' library.
// tsconfig.base.json maps the alias to the library's public entry point:
//   "paths": { "@acme/payments-core": ["libs/payments-core/src/index.ts"] }

// Flagged: a relative path that climbs out of billing-api into another project.
import { chargeCard } from '../../../../libs/payments-core/src/lib/stripe/charge';

// Flagged: a deep import past the alias into payments-core's internal files.
import { roundToMinorUnits } from '@acme/payments-core/src/lib/money/rounding';

// Allowed: the published alias, which resolves to libs/payments-core/src/index.ts.
// The payments team decides what index.ts exports, and that is the supported API.
import { chargeCard as charge, Money } from '@acme/payments-core';

export async function createInvoice(customerId: string, amount: Money) {
  return charge(customerId, amount);
}

// ---------------------------------------------------------------
// libs/payments-core/src/lib/refunds.ts
// Flagged: payments-core importing back into billing-api creates the cycle
// billing-api -> payments-core -> billing-api. The rule reports it even if
// the cycle runs through intermediate libraries.
// import { InvoiceStatus } from '@acme/billing-api';

// ---------------------------------------------------------------
// Rule config (flat-config style). Recent Nx versions use '@nx/enforce-module-boundaries'.
// Older versions used '@nrwl/nx/enforce-module-boundaries'. Check the docs for your installed version.
// rules: {
//   '@nx/enforce-module-boundaries': ['error', {
//     depConstraints: [], // no tags yet: deep-import and cycle checks still apply
//   }],
// }

Shows which cross-project imports the rule flags with no tags configured: relative and deep imports that bypass a library's public alias, and a circular dependency between two projects.

How does enforce-module-boundaries work?

The rule runs inside ESLint, so it is part of the same per-file lint pass as every other rule. What sets it apart is that it does not judge an import by the file alone. It uses the Nx project graph to work out which projects sit on either side of the import.

For each import statement in a linted file, it takes these steps:

  1. Find the source project. The rule looks up which project owns the file being linted, based on the project roots in the graph.
  2. Resolve the target. It resolves the import specifier. A path alias such as @acme/payments-core is matched against the workspace's TypeScript path mappings. A relative path is resolved against the file's location. A bare package name that maps to no workspace project is treated as an external (npm) import.
  3. Check the import's shape. If the target is another workspace project, the rule checks whether the import goes through that project's public alias. It flags a relative path that crosses a project root or a deep path into the other project's files.
  4. Check the graph. It looks for a path in the project graph from the target back to the source. If such a path exists, the new edge would close a cycle, and the rule reports it.
  5. Match tags against constraints. The rule collects every depConstraints entry whose sourceTag matches one of the source project's tags. The import must satisfy all of those entries. That means onlyDependOnLibsWithTags and notDependOnLibsWithTags for workspace projects, and allowedExternalImports and bannedExternalImports for npm packages.

All of this works because the graph already records every project, its root, its tags and its dependency edges. The rule reads that data and does not run its own analysis of the workspace. It also depends on the graph being current. If a project is missing from the graph or has the wrong root, the rule resolves imports against the wrong picture of the repo. For the same reason, it only sees dependencies that are expressed as resolvable imports. The section on when to avoid the rule covers what that leaves out.

Who should use enforce-module-boundaries?

The rule is aimed at teams working in an Nx monorepo where the import graph carries architectural meaning that nobody can hold in their head.

  • Platform and developer-experience engineers who own the workspace setup. They encode the layering and domain rules once, and every team gets them through lint.
  • Multi-team monorepos. When several teams share a repo and no single reviewer sees every change, the rule enforces ownership boundaries such as "billing does not import identity" without depending on who happens to review the pull request.
  • Repos with a layered library design. If you already split code into feature, data-access and util libraries, or into domain and infrastructure libraries, the type constraints keep those layers from collapsing into each other over time.
  • Teams planning to extract services or packages later. Clean boundaries inside the monorepo make it much easier to lift a domain out, because its dependencies are already explicit and point in one direction.
  • Teams that rely on nx affected and caching. Fewer and more predictable edges keep affected-project sets small and cache hits high.

It is less useful for a small repo owned by a single team, or when the boundaries that matter run between deployed services rather than between libraries. The last section covers those cases.

How do nx tags work, and how should you design a scope and type taxonomy?

A tag is a free-form string listed in a project's tags array, either in project.json or under the nx key in package.json. Nx gives tags no meaning. The boundary rule only checks whether a project's tags match the patterns you write, so scope:orders is as opaque to Nx as banana. The key:value format is a team convention. It is useful because it lets you reason about tags in groups, and many teams pair it with wildcard patterns in constraints.

Most repos need two independent axes:

  • Scope records domain ownership: scope:orders, scope:billing, scope:shared. It answers "whose code is this?"
  • Type records the layer: type:app, type:feature, type:data-access, type:util. It answers "what is this allowed to know about?"

Every project gets exactly one tag from each axis. The axes are checked separately, so a scope:billing, type:feature library has to satisfy both rules.

Source type May depend on
type:app feature, data-access, util
type:feature feature, data-access, util
type:data-access data-access, util
type:util util

Dependencies point downward. Utilities stay pure and cheap to reuse, and data-access never pulls in UI or orchestration logic.

Keep the taxonomy small. Every new tag value needs its own constraint, and engineers stop understanding a matrix with a dozen types. Watch scope:shared as well. It tends to become a dumping ground because anything placed there can be imported from everywhere. Before putting a library in shared, require that at least two domains already use it. Otherwise, keep it in its owning scope.

// eslint.config.mjs at the workspace root
import nx from '@nx/eslint-plugin';

export default [
  ...nx.configs['flat/base'],
  {
    files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],
    rules: {
      '@nx/enforce-module-boundaries': [
        'error',
        {
          depConstraints: [
            // Type axis: dependencies only point downward through the layers.
            { sourceTag: 'type:app', onlyDependOnLibsWithTags: ['type:feature', 'type:data-access', 'type:util'] },
            { sourceTag: 'type:feature', onlyDependOnLibsWithTags: ['type:feature', 'type:data-access', 'type:util'] },
            { sourceTag: 'type:data-access', onlyDependOnLibsWithTags: ['type:data-access', 'type:util'] },
            { sourceTag: 'type:util', onlyDependOnLibsWithTags: ['type:util'] },

            // Scope axis: a domain may use its own code plus shared, never another domain.
            { sourceTag: 'scope:orders', onlyDependOnLibsWithTags: ['scope:orders', 'scope:shared'] },
            { sourceTag: 'scope:billing', onlyDependOnLibsWithTags: ['scope:billing', 'scope:shared'] },
            // Shared must not reach back into any domain, or it stops being shared.
            { sourceTag: 'scope:shared', onlyDependOnLibsWithTags: ['scope:shared'] },
          ],
        },
      ],
    },
  },
];

// Each project carries one tag per axis, e.g. libs/billing/invoice-form/project.json:
//   "tags": ["scope:billing", "type:feature"]
// Both matching constraints apply. That library may import
// scope:billing or scope:shared projects, and only feature, data-access or util ones.

An ESLint flat config that encodes the type dependency matrix and the scope isolation rules as separate @nx/enforce-module-boundaries constraints, so every project must satisfy the constraint for each of its tags.

How do you write depConstraints for scope and type boundaries?

Each entry in depConstraints names a sourceTag and describes what projects carrying that tag may import. onlyDependOnLibsWithTags is an allowlist. For example, type:domain may depend only on type:domain and type:util. notDependOnLibsWithTags is a denylist. It is useful when the allowed set is large but one edge is forbidden, such as scope:billing never importing scope:identity.

Constraints are not alternatives. A project tagged scope:billing and type:data-access must satisfy the billing constraint and the data-access constraint at the same time. That combination is how the two axes work together. The scope rule restricts which domains a project can reach, and the type rule restricts which layers it can reach. An import is legal only if it passes both rules. You never need one constraint per scope and type pair.

A sourceTag: "*" entry matches every project, including untagged ones. Without any constraint that matches it, an untagged project cannot depend on libraries at all, which forces people to tag new projects. A catch-all with onlyDependOnLibsWithTags: ["*"] removes that pressure. Any project someone forgot to tag can then import anything, and nothing reports it. If you need a catch-all, keep it narrow or leave it out.

External packages follow the same model. Put bannedExternalImports on type:domain and type:util to keep HTTP framework packages such as express or fastify out of them. Ban your ORM and database driver from every type except type:data-access, so persistence stays in one layer. allowedExternalImports is the stricter option. It lists the only packages a tag may use, which suits domain libraries that should stay close to dependency-free.

// eslint.config.mjs (workspace root)
import nx from '@nx/eslint-plugin';

export default [
  ...nx.configs['flat/base'],
  {
    files: ['**/*.ts', '**/*.js'],
    rules: {
      '@nx/enforce-module-boundaries': ['error', {
        depConstraints: [
          // Scope axis: which business domains a project may reach.
          { sourceTag: 'scope:shared', onlyDependOnLibsWithTags: ['scope:shared'] },
          // Denylist: billing may use most scopes, but never identity.
          { sourceTag: 'scope:billing', notDependOnLibsWithTags: ['scope:identity'] },
          { sourceTag: 'scope:identity', onlyDependOnLibsWithTags: ['scope:identity', 'scope:shared'] },

          // Type axis: a project tagged scope:billing + type:domain must pass BOTH rules.
          { sourceTag: 'type:domain',
            onlyDependOnLibsWithTags: ['type:domain', 'type:util'],
            // Allowlist: domain code stays close to dependency-free.
            allowedExternalImports: ['zod', 'date-fns'] },
          { sourceTag: 'type:util',
            onlyDependOnLibsWithTags: ['type:util'],
            // No HTTP framework and no persistence in utilities.
            bannedExternalImports: ['express', 'fastify', '@fastify/*', '@prisma/client', 'pg'] },
          { sourceTag: 'type:feature',
            onlyDependOnLibsWithTags: ['type:feature', 'type:data-access', 'type:domain', 'type:util'],
            // Features reach the database only through data-access libraries.
            bannedExternalImports: ['@prisma/client', 'pg'] },
          // The one layer allowed to import the ORM and database driver.
          { sourceTag: 'type:data-access',
            onlyDependOnLibsWithTags: ['type:data-access', 'type:domain', 'type:util'] },

          // Deliberately no { sourceTag: '*', onlyDependOnLibsWithTags: ['*'] }:
          // untagged projects stay unable to import libraries until someone tags them.
        ],
      }],
    },
  },
];

A flat ESLint config where scope and type constraints apply together to each project, external package rules keep the ORM in data-access and HTTP frameworks out of domain and util libraries, and the permissive catch-all is left out on purpose.

How do you add module boundary rules to an existing Nx repo?

The rule earns its keep once more than one team or domain shares the repo. With one team, a misplaced import gets caught in review. With several teams, nobody owns the whole graph, and coupling builds up faster than reviewers notice it.

Roll the rule out in stages:

  1. Start permissive. Add a single constraint that lets any tag depend on any tag. The rule is now wired into lint, but nothing fails yet.
  2. Tag every project. Untagged projects slip past tag-based constraints, so finish this step before you tighten anything.
  3. Run nx graph. Compare the dependencies you actually have with the taxonomy you designed. The gap between the two is your backlog.
  4. Tighten one boundary at a time. Begin with the constraint that has the fewest violations. A small, finished change builds trust in the rule.
  5. Fix or whitelist each violation. You can add an exception through the rule's allow list or an inline ESLint disable. Each exception needs a named owner and a removal date, or it becomes permanent.

A big-bang fix stalls feature work and produces one huge, hard-to-review diff. Leaving violations as warnings without owners is worse. Warnings that nobody resolves teach engineers to ignore lint output.

Illustrative estimate. Assume 120 violations. Assume 70% are trivial import moves at 15 minutes each, and 30% need code extracted into a shared library at 3 hours each. That comes to about 21 + 108 = 129 engineer-hours. The extraction work drives the cost, so count those violations first.

// eslint.config.js (flat config) at the workspace root
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',
        {
          // Exceptions are temporary. Each entry needs an owner and a removal date.
          allow: [
            // OWNER: @payments-team  REMOVE BY: 2027-03-31
            // billing still imports legacy helpers that have not been extracted yet.
            '@acme/legacy-utils',
          ],
          depConstraints: [
            // Stage 4: the first tightened boundary. It was picked because
            // nx graph showed it had the fewest violations.
            {
              sourceTag: 'scope:billing',
              onlyDependOnLibsWithTags: ['scope:billing', 'scope:shared'],
            },
            // Stage 1: the permissive catch-all. Other scopes stay
            // unrestricted until it is their turn to be tightened.
            {
              sourceTag: '*',
              onlyDependOnLibsWithTags: ['*'],
            },
          ],
        },
      ],
    },
  },
];

A mid-rollout ESLint config where one boundary (scope:billing) has been tightened, a permissive catch-all still covers every other tag, and the single allowed exception is labeled with an owner and a removal date.

How do you enforce Nx library boundaries in CI?

Running the rule in CI keeps that bill from growing. On every pull request, run nx affected -t lint against the base branch. It lints the changed projects and every project that depends on them, which matters because a boundary violation can come from a new import in a dependent. Run nx run-many -t lint on the main branch or nightly as a full sweep. The rule reads the project graph, so lint cost grows with the number of projects and their dependents. Nx's computation cache, local or shared across CI agents, keeps that growth in check because unchanged projects replay their previous lint result instead of re-running ESLint.

Treat depConstraints and tags as architecture, not configuration. Put the root ESLint config and the tags fields in project.json files under CODEOWNERS, so a platform or architecture group reviews any change that loosens a boundary. Add a CI step that lists projects and fails when any project has an empty tag list. An untagged project is a gap that new code can grow into.

Know the bypass routes:

  • Inline suppressions. eslint-disable comments that name @nx/enforce-module-boundaries turn the rule off for a line or file. Run ESLint with --report-unused-disable-directives so stale suppressions get flagged, and have reviewers search diffs for the rule name. Strict repos can disable inline config entirely with --no-inline-config.
  • Skipped local hooks. Developers can skip lint locally, so CI must be the gate that blocks the merge.
  • Projects linted by other tools. A project linted by something other than ESLint never runs this rule, so it has no boundary check at all.

A rejected import at review costs minutes. The same coupling found during a later refactor costs the extraction hours estimated above.

How can enforce-module-boundaries save engineering time?

The time savings come from catching coupling at the cheapest point, which is the moment someone writes the import. Fixing it later is far more expensive.

  • Earlier feedback. With the rule enabled in the editor through the ESLint integration, an engineer sees the violation while typing. Without the rule, the mistake surfaces in code review at best. At worst it surfaces months later, when someone tries to change or extract the library.
  • Less architecture debate in review. Reviewers no longer have to spot and argue about forbidden imports by eye. The linter states the rule, and review time goes to logic and design.
  • Safer refactors inside a library. Consumers must go through the public entry point, so the owning team can rename or move internal files without searching the whole repo for deep imports.
  • Smaller affected sets in CI. Every unnecessary edge in the project graph widens what nx affected has to rebuild, test and lint when a library changes. Keeping edges deliberate keeps those sets smaller and makes cache hits more likely.
  • Cheaper extractions later. If a domain only depends on its own scope and scope:shared, moving it into a separate package or service is mostly mechanical. You avoid untangling hidden cross-domain imports.

Illustrative estimate. Assume a repo where reviewers raise 5 boundary-related comments a week. Assume each one costs 20 minutes of combined author and reviewer time to discuss and fix. That is about 100 minutes a week. Also assume that 1 such import a month slips through review. Using the earlier assumption of 3 hours per extraction to untangle it later, that adds roughly 36 hours a year. Under these assumed inputs, moving the check into lint recovers roughly 80 hours of review time plus about 36 hours of later cleanup per year. Even so, the rollout cost estimated earlier takes more than a year to pay back. Replace these inputs with counts from your own reviews and incident history before using the number to justify the work.

The savings depend on the rule being trusted. If it produces unexplained failures or a pile of unowned exceptions, engineers start working around it, and the time goes into suppressions instead.

How do you fix common enforce-module-boundaries violations?

Most violations fall into five patterns. The error text below is paraphrased, because exact wording varies between Nx versions. The fix depends on which way the dependency should point.

Violation Typical error (paraphrased) Fix
Lib imports an app Imports of apps are forbidden Extract the shared code into a new lib that both the app and the original lib depend on
type:util imports type:feature A project tagged type:util can only depend on libs tagged type:util Move the needed code down into a util, or move the importing code up into the feature
scope:billing imports scope:orders A project tagged scope:billing can only depend on libs tagged scope:billing or scope:shared Extract the common piece into a scope:shared lib
Deep import into libs/orders/src/lib/... Deep imports into another project are not allowed Export the symbol from the lib's public entry point and import it through the path alias
Circular dependency Circular dependency between A and B detected Define an interface in a lower lib, and have the higher lib supply the implementation

Don't settle a violation by adding the missing tag to the constraint. That approves the coupling without removing it. The deep-import fix matters because the entry point is the lib's contract. Anything reached through src can be renamed or deleted without warning.

For cycles, the inversion fix works because both libs end up depending on an abstraction. The lower lib owns the interface. The higher lib registers its implementation at composition time, usually through dependency injection or a factory passed in by the app.

Each of these fixes tends to create a lib. Strict boundaries therefore push teams toward many small libraries, and every new library adds overhead:

  • Its own project config
  • Path alias entries
  • Lint and test targets
  • Another node in the project graph

Budget for that overhead deliberately. Don't let it build up one extraction at a time.

When should you avoid relying on enforce-module-boundaries, and what are the alternatives?

The rule reads source files and checks imports that Nx can resolve to a project. Anything outside that path is invisible to it: a require() built from a variable, plugins loaded by string name, generated code that is not in the project graph, and dependencies declared only through implicitDependencies. Most backend coupling also happens at runtime, through HTTP calls, queue messages and shared database tables. Two services can be perfectly tagged and still break each other through a renamed column. The rule is also not a security control. Anyone can add an eslint-disable comment or edit depConstraints, and nothing stops the bundled code from loading whatever it wants at runtime.

The rule is a poor fit for a small repo owned by one team, where a code review catches the same mistakes with less setup. It is also a poor fit when your important boundaries are between deployed services rather than between libraries. In those cases, use it alongside other controls or replace it.

Approach What it enforces Cost
API contracts and contract tests Runtime compatibility between services You have to maintain schemas and tests
Separate repos or packages with versioning Explicit, versioned dependencies Coordinated releases are slower
Code ownership rules Who must approve changes It controls review, not structure
Language-level visibility (Go internal, Java modules, Kotlin internal) Compiler-checked access It is limited to one language

Expect the rules to drift over time:

  • Untagged projects match no constraint and slip through silently.
  • Renamed domains leave old tags that no longer match the rules.
  • Stale exceptions stay in the config long after the reason for them is gone.

Audit tags and exceptions on a fixed schedule.

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.
  • 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.