What does the Nx enforce-module-boundaries rule actually check?

The enforce-module-boundaries rule ships with Nx's ESLint plugin. It runs during normal linting, but it does more than inspect one file. For each import it finds, it resolves the target to a project in the Nx project graph. It then compares the source and target projects using three inputs:

  • The project graph, which tells the rule which project owns each file and which project an import resolves to.
  • Tags, the string labels declared in each project's configuration, such as scope:billing or type:data-access.
  • The depConstraints array, where each entry names a sourceTag and lists the tags that projects carrying it may depend on (onlyDependOnLibsWithTags) or must not depend on (notDependOnLibsWithTags).

If an import connects two projects in a way no constraint allows, lint fails at that line.

Some checks apply even before you write any constraints:

  • Circular dependencies. The rule flags project-level cycles, which would otherwise make build order and ownership ambiguous.
  • Relative imports that cross project boundaries. A path like ../../payments/src/... bypasses the graph entirely. Nx then cannot see the dependency for caching or affected-project calculations.
  • Deep imports into another library's internals. Importing a file behind a library's public entry point couples you to code its owners consider private.

Taken together, the tags and constraints act as an executable architecture spec. This matters most for backend and platform engineers running Nx monorepos with several domains or teams. In those repos, layering and ownership rules written in a wiki tend to erode one pull request at a time. When the rule is enforced in CI, every merge has to pass them.

Who should use module boundary rules?

The rule is worth adopting if you meet most of these conditions:

  • You run an Nx monorepo with several backend domains. Examples include orders, billing and identity living side by side as libraries and apps. Without boundaries, any library can import any other, and the graph drifts toward a tangle.
  • More than one team commits to the same repo. Tags give each team a domain it owns. The rule makes sure other teams reach that domain only through the surface the owners chose to expose.
  • You have a layering convention you want to keep. If your team agrees that repositories must not call use cases, or that entities must not perform I/O, the rule turns that agreement into a lint error rather than a review comment.
  • You expect to extract services later. Domains that only talk through contract libraries are much easier to split into separate deployables than domains that import each other's internals.
  • Platform or developer-experience engineers maintain the workspace. They usually own the ESLint config, the tag vocabulary and the CI checks described below.

It is a weaker fit for a small repo owned by one team with one domain. In that case, the tag vocabulary and constraint list cost more to maintain than they prevent. The final section covers alternatives for that case.

How does the rule work?

The mechanism has four steps, and they explain both what the rule can catch and what it cannot.

  1. Nx builds the project graph. Nx discovers projects from their configuration files and records each project's root directory and tags. It then analyzes source files to find dependencies between projects. ESLint does not build this graph itself. The rule reads the graph Nx has computed.
  2. The rule maps files and imports to projects. When ESLint visits a file, the rule finds the project whose root contains that file. For each import specifier, the rule resolves the target. Workspace path aliases defined in the root TypeScript config map to a library's entry point. Relative paths resolve to a file location, and from there to the project that owns it. If the target is the same project, the import is allowed. Boundary constraints apply only to imports that cross project boundaries.
  3. The rule checks structural problems. Before looking at tags, it flags relative imports that cross into another project, deep imports that bypass a library's entry point, and imports that would close a cycle in the project graph.
  4. The rule evaluates tag constraints. It collects every entry in depConstraints that matches the source project. A sourceTag entry matches if the project carries that tag. An allSourceTags entry matches only if the project carries all listed tags. The * wildcard matches any project. The target's tags must then satisfy every matching constraint: each onlyDependOnLibsWithTags list must contain at least one of the target's tags, and no notDependOnLibsWithTags list may contain any of them. If any matching constraint fails, the rule reports an error on that import line.

Two consequences follow. First, the rule only knows what the project graph knows. Anything that is not an import between projects, such as an HTTP call or a shared database table, is invisible to it. Second, a project with no tags, or with a misspelled tag, may match no constraint at all and pass silently. This is why the rollout section below adds a tag-validation script.

How should you design a two-axis tag vocabulary for backend libraries?

Give every project exactly two tags: one for the domain it belongs to and one for its layer. Use a fixed prefix for each axis, scope: for domain and type: for layer, so that a glance at a tag tells you which axis it describes. In project.json, an orders repository library gets "tags": ["scope:orders", "type:data-access"], the billing service gets ["scope:billing", "type:app"], and a shared logging helper gets ["scope:shared", "type:util"].

The axes must stay separate. A combined tag such as orders-data-access encodes both facts in one string. You then need a tag for every domain/layer pair, and each constraint has to list the specific pairs it allows. With five domains and six layers that is thirty tags. Adding a sixth domain means adding six more tags and editing every rule that names them.

Separate tags avoid this because Nx checks every constraint whose sourceTag matches the project, and the import must satisfy all of them. You write one rule set for layers and one for domains, and each axis grows on its own. Adding a domain is one new scope: constraint, and the layer rules stay untouched.

Type tag What belongs in it
type:app Deployable entry point: bootstrap, config wiring, process lifecycle
type:api A domain's public contract: DTOs, client interfaces, events other domains may import
type:feature Use cases and orchestration for one domain capability
type:data-access Repositories, ORM mappings, external service clients
type:domain Entities, value objects, business rules with no I/O
type:util Pure, domain-agnostic helpers such as date math or ID generation
// eslint.config.mjs (workspace root)
import nx from '@nx/eslint-plugin';

export default [
  ...nx.configs['flat/base'],
  {
    files: ['**/*.ts'],
    rules: {
      '@nx/enforce-module-boundaries': ['error', {
        enforceBuildableLibDependency: true,
        allow: [],
        depConstraints: [
          // Layer axis: written once, applies to every domain.
          { sourceTag: 'type:app',
            onlyDependOnLibsWithTags: ['type:feature', 'type:api', 'type:data-access', 'type:domain', 'type:util'] },
          { sourceTag: 'type:feature',
            onlyDependOnLibsWithTags: ['type:api', 'type:data-access', 'type:domain', 'type:util'] },
          { sourceTag: 'type:data-access',
            onlyDependOnLibsWithTags: ['type:domain', 'type:util'] },
          { sourceTag: 'type:api',
            onlyDependOnLibsWithTags: ['type:util'] },
          { sourceTag: 'type:domain',
            onlyDependOnLibsWithTags: ['type:util'] },
          { sourceTag: 'type:util',
            onlyDependOnLibsWithTags: ['type:util'] },

          // Domain axis: adding a domain means adding one entry here.
          { sourceTag: 'scope:orders',
            onlyDependOnLibsWithTags: ['scope:orders', 'scope:shared'] },
          { sourceTag: 'scope:billing',
            onlyDependOnLibsWithTags: ['scope:billing', 'scope:shared'] },
          { sourceTag: 'scope:shared',
            onlyDependOnLibsWithTags: ['scope:shared'] },
        ],
      }],
    },
  },
];

An ESLint flat config in which layer and domain constraints are written as two independent rule sets, so an import from a project tagged scope:orders and type:data-access must satisfy both its scope rule and its type rule.

How do you write depConstraints for layers and domains?

Treat the layers as a directed graph. An edge means "may import from," and anything not drawn is forbidden:

Edge Why it exists
app → feature Apps wire up transports (HTTP, queues) and delegate the actual work
feature → domain, data-access, util Use cases orchestrate rules and persistence
data-access → domain, util Repositories map rows to entities, so they need the entity types
domain → util Business rules stay free of I/O and can be tested in isolation
util → util Helpers may compose, but never reach upward

Each type:* tag gets one constraint whose onlyDependOnLibsWithTags lists exactly its outgoing edges. Domain isolation follows the same pattern: the scope:orders constraint allows only scope:orders and scope:shared.

The two axes compose. Nx checks every constraint whose sourceTag matches the importing project, and the import must pass all of them. A data-access library in scope:orders can therefore import scope:orders + type:domain. It cannot import scope:billing + type:domain, because that fails the scope rule, and it cannot import scope:orders + type:feature, because that fails the layer rule. Neither axis overrides the other.

Some rules only apply to the intersection of two tags. allSourceTags: ["scope:shared", "type:util"] matches only projects that carry both tags. Pair it with notDependOnLibsWithTags listing every domain scope. A deny-list is clearer here because the intent is a prohibition. An equivalent allow-list would need updating every time a new tag appears, and it would hide the reason the rule exists.

The full config needs one constraint per layer, one per domain scope, scope:shared restricted to itself, and the intersection rule. All of these go in the depConstraints array of the module boundaries rule.

// eslint.config.mjs (workspace root)
// Layers:  app -> feature -> data-access -> domain -> util (-> util)
//                  feature ---------------> domain, util
import nx from '@nx/eslint-plugin';

export default [
  ...nx.configs['flat/base'],
  {
    files: ['**/*.ts'],
    rules: {
      '@nx/enforce-module-boundaries': ['error', {
        depConstraints: [
          // Layer axis: each list is exactly that layer's outgoing edges
          { sourceTag: 'type:app', onlyDependOnLibsWithTags: ['type:feature'] },
          { sourceTag: 'type:feature', onlyDependOnLibsWithTags: ['type:domain', 'type:data-access', 'type:util'] },
          { sourceTag: 'type:data-access', onlyDependOnLibsWithTags: ['type:domain', 'type:util'] },
          { sourceTag: 'type:domain', onlyDependOnLibsWithTags: ['type:util'] },
          { sourceTag: 'type:util', onlyDependOnLibsWithTags: ['type:util'] },

          // Domain axis: a domain sees itself plus shared, never a sibling domain
          { sourceTag: 'scope:orders', onlyDependOnLibsWithTags: ['scope:orders', 'scope:shared'] },
          { sourceTag: 'scope:billing', onlyDependOnLibsWithTags: ['scope:billing', 'scope:shared'] },
          { sourceTag: 'scope:shared', onlyDependOnLibsWithTags: ['scope:shared'] },

          // Intersection: matches only projects tagged BOTH shared and util.
          // A deny-list states the prohibition directly; add new domains here.
          {
            allSourceTags: ['scope:shared', 'type:util'],
            notDependOnLibsWithTags: ['scope:orders', 'scope:billing'],
          },
        ],
      }],
    },
  },
];

A flat ESLint config where every constraint matching an importing project's tags must pass, so the layer rules, the domain-scope rules and the shared-util intersection rule apply together and none overrides another.

How should one backend domain call another without loosening the rules?

The contract pattern gives another domain a narrow, deliberate surface to import while leaving the domain's internals closed. Create a dedicated library such as libs/orders/api, tagged scope:orders and type:api. It holds only what callers need to talk to orders: DTOs like OrderSummaryDto and interfaces like OrdersQueryPort. It contains no implementations, no ORM entities, and no framework wiring.

Next, extend each domain constraint so that onlyDependOnLibsWithTags for scope:billing lists scope:billing, scope:shared, and type:api. Then add a constraint for sourceTag: "type:api" that allows only type:api and scope:shared. Without that second rule, a contract library could start importing its own domain's data-access code, and every consumer would pull that code in transitively.

Inside the contract library, src/index.ts is the whole public surface. It should contain only lines like export type { OrderSummaryDto } from './lib/order-summary.dto' and export type { OrdersQueryPort } from './lib/orders-query.port'. Consumers import through the workspace path alias, which resolves to this file. Anything not re-exported there is effectively private. The orders domain implements OrdersQueryPort in its own data-access layer and provides it through dependency injection. Billing depends on the interface and never sees the implementation.

There are two shortcuts to avoid. Adding scope:orders to billing's allowed tags fixes one error, but it also exposes repositories, entities, and helpers across the whole domain. An eslint-disable comment is worse: it silences one line, leaves the project graph showing a coupling nobody approved, and invites the next developer to copy it.

// libs/orders/api/src/index.ts: the entire public surface of the contract lib.
// Type-only re-exports. Anything not listed here stays private to the library.
export type { OrderSummaryDto } from './lib/order-summary.dto';
export type { OrdersQueryPort } from './lib/orders-query.port';

// eslint.config.mjs (excerpt): Nx flat config
import nx from '@nx/eslint-plugin';

export default [
  ...nx.configs['flat/base'],
  {
    files: ['**/*.ts'],
    rules: {
      '@nx/enforce-module-boundaries': ['error', {
        depConstraints: [
          // Billing may use its own code, shared code, and any contract lib.
          // It still cannot reach scope:orders internals.
          { sourceTag: 'scope:billing',
            onlyDependOnLibsWithTags: ['scope:billing', 'scope:shared', 'type:api'] },
          { sourceTag: 'scope:orders',
            onlyDependOnLibsWithTags: ['scope:orders', 'scope:shared', 'type:api'] },
          // Contract libs stay thin. They must not pull in data-access or
          // feature code, which every consumer would otherwise inherit.
          { sourceTag: 'type:api',
            onlyDependOnLibsWithTags: ['type:api', 'scope:shared'] },
        ],
      }],
    },
  },
];

This example shows the scope:orders / type:api contract library exposing only type re-exports from its index.ts, plus the dependency constraints that let other domains import contracts but keep contract libraries from depending on domain internals.

How do you roll out module boundaries in an existing Nx repo and keep them enforced?

Adopt boundaries once a repo has more than one team or more than a few domains. Before that, the rules mostly add ceremony. After that, every month without them adds edges you will have to unwind later.

Start by auditing what already exists. Open nx graph, focus on one domain at a time, and note which edges cross domain or layer lines. This gives you a list of known violations before any rule exists. Next, tag every project with one scope: and one type: tag. Keep a single wildcard constraint (sourceTag: '*', onlyDependOnLibsWithTags: ['*']) so tagging alone breaks nothing. Then add real constraints one tag at a time, beginning with the cleanest domain, and fix its violations before moving to the next.

Running the rule as a warning during migration keeps the build green, but warnings pile up and people learn to ignore them. A better split: set the rule to error, and only add constraints for domains you have already cleaned. This way, nothing is merely advisory.

Three things keep the rules in place:

  • Lint affected projects in CI. A change that adds a forbidden import fails in its own pull request.
  • Validate tags with a small script. Tags are free-form strings, so scope:biling passes silently and matches no constraint. Read each project.json and fail when a project lacks exactly one scope:* and one type:* tag from an allowed list.
  • Set tags through generator defaults. New libraries then start correctly tagged.

The payoff is timing. A reviewer can reject a cross-domain import in minutes. Discovering that same coupling while extracting a service can cost a sprint.

// tools/check-tags.js: run in CI with `node tools/check-tags.js`
// Tags are free-form strings, so a typo like scope:biling matches no constraint
// and passes lint silently. This fails the build instead.
const fs = require('fs');
const path = require('path');

const ALLOWED = {
  scope: ['billing', 'orders', 'identity', 'shared'],
  type: ['api', 'feature', 'data-access', 'domain', 'util'],
};
const SKIP = new Set(['node_modules', 'dist', '.git', '.nx', 'tmp']);

// Find every project.json. Projects defined only in package.json are not covered here.
function findProjects(dir, out = []) {
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    if (SKIP.has(entry.name)) continue;
    const full = path.join(dir, entry.name);
    if (entry.isDirectory()) findProjects(full, out);
    else if (entry.name === 'project.json') out.push(full);
  }
  return out;
}

const errors = [];
for (const file of findProjects(process.cwd())) {
  const { name = file, tags = [] } = JSON.parse(fs.readFileSync(file, 'utf8'));
  for (const [prefix, allowed] of Object.entries(ALLOWED)) {
    const matching = tags.filter((t) => t.startsWith(`${prefix}:`));
    // Require exactly one tag per dimension, with a known value.
    if (matching.length !== 1) {
      errors.push(`${name}: expected exactly one ${prefix}:* tag, found ${matching.length}`);
    } else if (!allowed.includes(matching[0].slice(prefix.length + 1))) {
      errors.push(`${name}: unknown tag "${matching[0]}"`);
    }
  }
}

if (errors.length) {
  console.error(errors.join('\n'));
  process.exit(1);
}
console.log('All projects have one valid scope and one valid type tag.');

A dependency-free Node script for CI that reads every project.json and fails when a project lacks exactly one scope: and one type:* tag from an allowed list. This catches tag typos that would otherwise slip past the module-boundary lint rule.*

How do you read and fix common module boundary violations?

When the lint step fails, the message names the importing project, the imported project, and the category of problem. The category tells you which fix applies. Changing tags to make the error disappear is almost always the wrong move, because the tags encode the architecture you agreed on.

Violation Usual cause Fix
Tag constraint A library imports a project whose tags are not in its allowed list, for example a type:data-access lib pulling in type:feature, or domain:billing reaching into domain:orders. Move the shared code down a layer, or route the call through the target domain's public API library.
Deep import The import path reaches past the library's entry point into internal files, or a relative path crosses a project root. Export the symbol from the library's public index and import through the workspace path alias. If it shouldn't be public, the caller shouldn't use it.
Circular dependency Two libraries import each other, often through a type that ended up in the wrong place. Extract the shared types or contracts into a lower-level library both can depend on, or invert the dependency behind an interface.
Lazy or dynamic import An import() call was assumed to escape analysis. Treat it like a static import. The project graph still records the edge, so it must satisfy the same constraints.

For cycles, run nx graph and focus on the two projects named in the error. Seeing the full path usually shows which file introduced the back-edge.

How can module boundaries save engineering time?

The time savings come from moving architecture checks to the cheapest point in the workflow and from keeping the project graph accurate.

  • Violations are caught when they are cheapest to fix. A forbidden import flagged in the editor or in the pull request that introduced it is usually a one-file change. The same import found months later may have callers built on top of it, and unwinding it means touching every one of them.
  • Reviewers stop checking layering by hand. Without the rule, someone has to read every import in every pull request and remember which domains may talk to which. With the rule, review can focus on behavior, and the layering question is already answered by CI.
  • Affected-project calculations stay meaningful. Nx uses the project graph to decide which projects a change affects. When domains don't import each other's internals, a change inside scope:billing affects billing and its consumers rather than large parts of the repo. That keeps nx affected runs and cached task results useful instead of rebuilding and retesting projects that only depend on billing by accident.
  • Service extraction and ownership changes are cheaper. If billing only reaches orders through libs/orders/api, moving orders to its own deployable means replacing the in-process implementation of OrdersQueryPort with a remote one. Billing code does not change. Without boundaries, the same extraction starts with an archaeology project to find every hidden import.
  • Onboarding is faster. A new engineer can read the depConstraints array and learn the allowed architecture in one place, and the linter corrects them before a reviewer has to.

An illustrative estimate, using assumed inputs rather than measured data: assume a team merges 4 cross-domain or cross-layer imports per month that nobody would have approved. Assume each one takes 15 minutes to fix when lint flags it in the original pull request. Assume each one takes 4 hours to unwind if it is discovered later, because callers have built on it. Under those assumptions, catching all four at merge time costs 1 hour per month, while discovering them later costs 16 hours. Your inputs will differ. The structure of the calculation is the point: the cost of a violation grows with the time it stays in the codebase, and the rule fixes that time at zero.

When should you avoid strict boundary rules, and what are the alternatives?

The rule enforces code coupling, not system coupling. It sees only linted files and the edges in the project graph. An HTTP call from orders to billing, a queue consumer that depends on another domain's message shape, or two domains reading the same database table never shows up as an import, so none of them is checked. Files outside lint coverage, such as scripts or generated code, also pass unchecked. A clean lint run tells you the import structure matches your tags. It does not tell you the design is sound.

The rule also has development costs:

  • Fine-grained tags cause churn. Every new tag needs constraint updates, and engineers start reaching for eslint-disable when a legitimate dependency is blocked.
  • Many small libraries add overhead. More projects mean more graph and cache work, and a cross-domain refactor touches many libraries at once.
  • scope:shared grows. Shared code is the easy way out of a violation, so it collects code that belongs to one domain.
  • Changing boundaries is expensive. Moving a domain boundary means retagging projects and moving code between them.
Alternative Fits better when
Separate repositories or packages Teams release independently and versioned contracts are acceptable
TypeScript project references You mainly need compile-time isolation and incremental builds
General-purpose import-restriction lint rules A few path bans are enough and you don't need a tag taxonomy
Architecture tests You need to check rules lint can't express, such as naming or how layers are used
Code review conventions The repo is small, one team owns it, and tag overhead isn't worth it

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.