Skip to main content

Nx + Hexagonal Architecture

Nx is a build system optimized for monorepos. Combined with hexagonal architecture, it enforces the boundaries that keep code maintainable as systems scale.

Why Nx for Hex

Hexagonal architecture separates domain logic from infrastructure. Nx enforces this separation through library boundaries:

apps/           → Entry points (Next.js, NestJS)
libs/
domain/ → Business logic, entities, use cases
ports/ → Interfaces (what the domain needs)
adapters/ → Implementations (databases, APIs, UI)
shared/ → Utilities, types, constants

The dependency rule: adapters depend on ports depend on domain. Nx's @nx/enforce-module-boundaries lint rule makes this a build error, not a code review comment.

Library Types

TypeHex LayerContains
featureAdaptersSmart components with data access
uiAdaptersPresentational components
data-accessAdaptersAPI clients, state management
domainDomainEntities, use cases, business rules
utilSharedLow-level utilities

Key Commands

# Visualize dependencies
nx graph

# Run affected tests only
nx affected --target=test

# Generate library with boundaries
nx g @nx/react:lib auth --directory=domain

Why This Matters

  • Caching — Nx only rebuilds what changed
  • Boundaries — Architecture violations fail the build
  • Scaling — Add apps without duplicating domain logic
  • AI-assisted dev — Clear structure helps AI understand the codebase

Resources

Context