What are Nx library types for backend code, and how do the layers depend on each other?

Nx does not ship built-in library types. "util", "domain", "data-access" and "feature" are naming conventions. They become meaningful only when each type is defined by the direction its imports are allowed to point. A library named domain that imports a database client is a data-access library with a misleading name. Folder names describe intent. Dependency rules are what the tooling can check.

For a backend service, the graph runs in one direction:

app/feature → data-access → domain → util

The app/feature layer may also import domain and util directly. Nothing points back up. The domain layer declares the interfaces it needs, such as a repository contract. Data-access implements them. This keeps business rules free of driver, ORM or network concerns, so they can be tested without infrastructure.

Layer May import Must not import Why
util other util only domain, data-access, app/feature Generic helpers must stay reusable by every layer
domain util data-access, app/feature Business rules should not depend on storage or transport
data-access domain, util app/feature Persistence maps to domain types but knows nothing about HTTP or queues
app/feature all of the above other apps Composition, wiring and transport live at the edge

Frontend types do not carry over cleanly. A frontend ui library holds presentational components, and backends have no equivalent. The closest match is controllers and serializers, which belong to a specific transport and usually stay in the app. A frontend feature library combines routing and state. On the backend, that composition role is filled by the app's module wiring. For that reason, many backend workspaces leave out ui and treat feature as optional.

+-------------------------------------------+
|  app / feature                            |
|  controllers, serializers, module wiring  |
+-------------------------------------------+
     |                 |                |
     v                 |                |
+------------------+   |                |
|  data-access     |   |                |
|  repo impls, ORM |   |                |
+------------------+   |                |
     |        |        |                |
     |        v        v                |
     |   +--------------------------+   |
     |   |  domain                  |   |
     |   |  entities, rules,        |   |
     |   |  repository interfaces   |   |
     |   +--------------------------+   |
     |                 |                |
     v                 v                v
+-------------------------------------------+
|  util   generic helpers (util -> util)    |
+-------------------------------------------+

  ---> : "may import" (dependency direction)
  data-access implements interfaces declared in domain
  no arrow ever points upward; apps never import other apps

Backend Nx library layers as one-way import rules: app/feature may import data-access, domain and util; data-access imports domain and util and implements domain's repository interfaces; domain imports only util; util imports only other util libraries.

What belongs in domain, data-access and util libraries?

Domain

A domain library holds entities, value objects, domain errors, and pure business rules such as "an order cannot be refunded after settlement." It also declares the ports the domain needs: repository and gateway interfaces like OrderRepository, written in domain terms. It must not import a framework, an ORM, an HTTP client, or anything else that performs I/O. Keeping it free of those imports means you can unit-test every rule with plain objects and in-memory fakes, with no database and no DI container to start. It also means a change of ORM or framework never forces a change to your business rules.

Data-access

A data-access library implements those ports. It contains ORM models or schemas, query code, repository implementations, external API clients, and cache adapters. It also owns the mapping between persistence shapes and domain objects. That mapping belongs here because only this layer knows both sides. If it lived anywhere else, column names and nullable foreign keys would leak into the domain. The example below shows the pattern: an OrderRepository port in domain, and a data-access class that implements it, using a mapper to turn rows into Order entities.

Util

A util library holds genuinely generic helpers: date arithmetic, retry wrappers, string and collection functions. Domain logic often ends up here because "util" sounds harmless. To check a helper, ask whether it would still make sense in an unrelated codebase. A function like chunk(array, size) passes that test. A function like calculateLateFee(invoice) fails it: it encodes a business rule, so it belongs in domain.

// libs/orders/domain/src/order-repository.ts (no ORM, no I/O imports)
export type OrderStatus = 'open' | 'settled' | 'refunded';

export class Order {
  constructor(readonly id: string, readonly status: OrderStatus, readonly totalCents: number) {}
  // Pure business rule, testable with plain objects
  canRefund(): boolean { return this.status !== 'settled'; }
}

// Port declared in domain terms; data-access implements it
export interface OrderRepository {
  findById(id: string): Promise<Order | null>;
}

// libs/orders/data-access/src/sql-order-repository.ts
import { Order, OrderRepository, OrderStatus } from '@acme/orders/domain';

// Persistence shape: column names and nullability stay in this layer
interface OrderRow { order_id: string; status_code: string; total_cents: number | null; }

// Minimal query interface; wire your real DB client in here
interface Db { queryOne<T>(sql: string, params: unknown[]): Promise<T | null>; }

// Mapper owns the row <-> entity translation
export function toOrder(row: OrderRow): Order {
  return new Order(row.order_id, row.status_code as OrderStatus, row.total_cents ?? 0);
}

export class SqlOrderRepository implements OrderRepository {
  constructor(private readonly db: Db) {}

  async findById(id: string): Promise<Order | null> {
    const row = await this.db.queryOne<OrderRow>(
      'SELECT order_id, status_code, total_cents FROM orders WHERE order_id = $1', [id]);
    return row ? toOrder(row) : null;
  }
}

An OrderRepository port and Order entity in the domain library, implemented in data-access by a SQL repository whose mapper converts database rows into domain entities.

How do you enforce boundaries with Nx tags and the module boundaries lint rule?

Give every project two tags in its project configuration: a type: tag (type:domain, type:data-access, type:util) and a scope: tag naming its bounded context (scope:billing, scope:orders, scope:shared). Then configure the depConstraints option of the Nx enforce-module-boundaries ESLint rule with one set of constraints per dimension. For example, type:data-access may depend on type:domain and type:util, and scope:billing may depend only on scope:billing and scope:shared.

Each constraint is checked on its own, so an import has to satisfy both dimensions. A billing data-access library importing the orders domain library passes the type check, because data-access may use domain code. It fails the scope check, because billing may not reach into orders. Neither dimension catches this alone.

Each library should expose a narrow index.ts entry point. The rule judges an import by which project it resolves to, so the entry point is the contract the rule enforces. Deep imports into another library's src/ folder, through relative paths or hand-added path aliases, turn internal files into public API. They can also resolve in ways the project graph does not record as a dependency. When that edge is missing, an affected run skips consumers that will in fact break.

The rule has limits:

  • Dynamic imports: a specifier computed at runtime cannot be analyzed statically.
  • Path tricks: require calls built from variables, and other path tricks, escape it too.
  • Untagged projects: these may fall outside your constraints. Add a catch-all constraint and treat a missing tag as a CI failure.
  • Locally disabled rules: an eslint-disable comment silences the rule for that file or line. Review those comments the way you would review a dependency change.
// eslint.config.mjs (workspace root)
// Each project carries two tags, e.g. libs/billing/data-access/project.json:
//   "tags": ["scope:billing", "type:data-access"]
import nx from '@nx/eslint-plugin';

export default [
  ...nx.configs['flat/base'],
  ...nx.configs['flat/typescript'],
  {
    files: ['**/*.ts'],
    rules: {
      '@nx/enforce-module-boundaries': [
        'error',
        {
          enforceBuildableLibDependency: true,
          allow: [],
          // Every constraint whose sourceTag matches must pass, so an import
          // has to satisfy both the type: and the scope: dimension.
          depConstraints: [
            // Layering (type:)
            { sourceTag: 'type:data-access', onlyDependOnLibsWithTags: ['type:domain', 'type:util'] },
            { sourceTag: 'type:domain', onlyDependOnLibsWithTags: ['type:domain', 'type:util'] },
            { sourceTag: 'type:util', onlyDependOnLibsWithTags: ['type:util'] },

            // Bounded contexts (scope:)
            // billing data-access -> orders domain passes the type check above
            // but fails here, because scope:orders is not in the list.
            { sourceTag: 'scope:billing', onlyDependOnLibsWithTags: ['scope:billing', 'scope:shared'] },
            { sourceTag: 'scope:orders', onlyDependOnLibsWithTags: ['scope:orders', 'scope:shared'] },
            { sourceTag: 'scope:shared', onlyDependOnLibsWithTags: ['scope:shared'] },

            // No { sourceTag: '*', onlyDependOnLibsWithTags: ['*'] } entry:
            // a project whose tags match no constraint is reported when it
            // depends on another library, so a missing tag fails lint in CI.
          ],
        },
      ],
    },
  },
];

A flat ESLint config for the Nx enforce-module-boundaries rule. It has one set of depConstraints for the type: dimension and one for the scope: dimension, so a billing data-access library importing the orders domain library passes the type check but fails the scope check.

Where should cross-cutting backend concerns live?

Configuration loading, database connection setup and dependency-injection wiring all depend on the runtime: environment variables, connection pools, framework decorators. If any of them leaks into a domain library, that library can no longer be tested or reused without the framework, and the lint rule from the previous section stops protecting anything meaningful.

Composition roots and adapters

Put the wiring at the edges. Each application is the composition root. Its bootstrap code reads configuration, validates it once and binds concrete implementations to the interfaces the domain declares. Data-access libraries hold the adapters: repository implementations, the ORM or driver setup, and the framework module that exports them. The domain library defines a repository interface and depends on nothing. The data-access library implements it, and the app chooses which implementation to inject. Util libraries stay pure, so a config parser that touches process.env does not belong there. It belongs in the app or in a dedicated config library tagged as data-access.

Per-context folders versus a global shared folder

Default to grouping by bounded context: libs/orders/domain, libs/orders/data-access, libs/billing/domain. Tags such as scope:orders then stop billing from importing orders internals. A top-level libs/shared folder tends to collect anything nobody wanted to own, and every change to it marks most of the workspace as affected.

A cross-context shared library is justified when the code is genuinely context-free, such as a logging adapter, a pagination type or an ID generator. It also needs a named owner and should change rarely. If the code encodes business rules, keep it inside its context.

// libs/orders/domain/src/index.ts (no framework, no env, no driver imports)
export interface Order { id: string; customerId: string; totalCents: number }
export interface OrderRepository { findById(id: string): Promise<Order | null> }
export class OrderService {
  constructor(private readonly orders: OrderRepository) {}
  getOrder(id: string) { return this.orders.findById(id); }
}

// libs/orders/data-access/src/index.ts (adapter: owns SQL and the driver boundary)
import type { Order, OrderRepository } from '@acme/orders/domain';
export type Query = <T>(sql: string, params: unknown[]) => Promise<T[]>;
export class SqlOrderRepository implements OrderRepository {
  constructor(private readonly query: Query) {}
  async findById(id: string): Promise<Order | null> {
    const rows = await this.query<Order>(
      'SELECT id, customer_id AS "customerId", total_cents AS "totalCents" FROM orders WHERE id = $1',
      [id],
    );
    return rows[0] ?? null;
  }
}

// apps/orders-api/src/main.ts (composition root: the only place that reads process.env)
import { OrderService } from '@acme/orders/domain';
import { SqlOrderRepository } from '@acme/orders/data-access';
import { createQuery } from './db'; // app-local pool setup, built from config below

function loadConfig() {
  const databaseUrl = process.env.DATABASE_URL; // e.g. postgres://app:changeme@localhost:5432/orders
  if (!databaseUrl) throw new Error('DATABASE_URL is required');
  return { databaseUrl };
}

const config = loadConfig(); // validated once, at startup
const orderService = new OrderService(new SqlOrderRepository(createQuery(config.databaseUrl)));
// Tests can construct OrderService with an in-memory OrderRepository instead.

The orders domain library declares a repository interface. The data-access library implements it with SQL. The app's composition root is the only place that reads configuration and binds the concrete adapter.

How does the layer split save build and test time with affected commands?

Nx builds a project graph from the imports between projects. Affected commands such as nx affected -t test compare your branch with a base commit, find the projects whose files changed, and walk the graph to select every project that depends on them. Only those projects run the target. The split pays off because the graph's shape decides how far a change spreads. Domain and util libraries are small and change rarely, so they seldom trigger anything. Data-access libraries change more often, but each one is imported by only the few services that use that store.

Illustrative estimate (assumed numbers, not a benchmark)

Assume 20 services, each with a 3-minute test suite, run serially. orders-data-access is imported by 3 services.

  • Formula: test time ≈ Σ (test duration of each affected project)
  • Change to orders-data-access: 3 services × 3 min, plus the library's own 1-minute suite = 10 minutes
  • Full run: 20 × 3 min = 60 minutes

Now assume the repository also has a catch-all shared library that holds a logger, DTOs, ORM entities and helper functions, and that 18 services import it. Because it mixes concerns, almost every feature touches it. A change there affects 18 services, or 54 minutes, close to a full run. The graph is still correct. The problem is that one high-churn node sits upstream of almost everything, so nearly every pull request marks nearly every project as affected.

Affected computation is file-level per project, not symbol-level. Nx cannot tell that only the logger changed. Splitting the catch-all into separate libraries is what limits each change to the projects that actually depend on it.

When should you avoid this layering, and what are the alternatives?

The three-layer split pays off when several services and teams share code, because tags and lint rules replace review-time arguments about who may import what. In a workspace with one or two services, the configuration, tag definitions and extra project files cost more than they save. There are rarely enough consumers to justify a boundary, and affected-based savings are small when nearly every change touches the same service anyway.

Even in larger workspaces, the split has costs:

  • Mapper drift. Keeping ORM entities out of the domain means writing mappers in data-access. Every new column needs an entity field, a domain field and a mapping line. When someone skips the last one, the value is dropped without an error.
  • Indirection without payoff. Ports-and-adapters justifies a repository interface by the chance of swapping persistence. If the database will never change, each interface is an extra file to navigate, and its only remaining benefit is test doubles.
  • Over-fine splitting. One library per entity multiplies project files, and the project graph, lint and editor tooling slow as the project count grows. Split along bounded contexts, not tables.
Approach Development cost Fits
Per-service libs only Lowest One or two services, little shared logic
Single shared lib Low at first, rising later Early stage; becomes the catch-all described above
Domain + data-access merged, util separate Moderate Multiple services, one stable persistence stack
Full three-layer split Highest Many services and teams, real need to isolate persistence

How do you adopt the split incrementally in an existing monorepo?

Treat the migration as a series of small, reviewable steps, not a single restructuring PR.

  1. Tag what already exists. Add scope: and type: tags to every current project before moving any files. A large legacy library can carry a provisional tag such as type:data-access until it is split. Tagging changes no import paths, so it merges cleanly and gives the lint rule something to evaluate.

  2. Run the module boundaries rule at warning severity. Warnings show you the real dependency graph without blocking CI. Read the violation list and use it as your backlog, since it shows exactly which imports cross layers.

  3. Extract interfaces before implementations. Move entity types, repository interfaces and domain errors into a new domain library first. Re-export them from their old location so existing consumers keep compiling. Then move the concrete implementations into data-access. Done in this order, the interfaces only move once, and the implementations can migrate one consumer at a time.

  4. Sequence moves to limit churn. Each move rewrites import paths in every file that consumes the code. Move one library per PR and merge it quickly. Schedule large moves when there are few open branches touching that scope. Remove the temporary re-exports once no code imports the old path.

  5. Tighten per scope. When a scope has no warnings left, switch its constraints to errors. This stops regressions in finished areas while other scopes are still being migrated.

  6. Revisit granularity. Some bounded contexts will only ever need one data-access library. Others will need several. Merge or split libraries based on how often they change together.

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 library types backend, 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.