Software Architecture

Hexagonal Architecture (Ports & Adapters) in Frontend Applications

Stop rewriting business rules every time an API SDK, storage engine, or UI framework churns. Hexagonal Architecture isolates pure domain logic behind typed ports so React, fetch, and IndexedDB stay swappable adapters.

About this page
READ
4 min
Interactive Simulator

Hexagonal Command Flow & Adapter Swap

Trace a checkout command across driving adapter, pure domain core, and swappable driven adapters without inverting dependency direction.

Composition Root
UI Driving Adapter
Pure Domain Core
Driven Adapter (HTTP / Fake)
Step 1 / 5: 1. Composition Root Wires Port

At boot, the composition root injects a concrete OrderGateway adapter (HttpOrderAdapter in prod, InMemoryOrderAdapter in tests) into the domain factory.

const submitOrder = createSubmitOrder(httpOrderAdapter);
Internal State / Memory
dependencyDirection
outer -> inner
domainImports
[]
wiredAdapter
HttpOrderAdapter
Hexagonal Command Flow & Adapter Swap

Under the Hood#

Hexagonal Architecture enforces an inward-only dependency rule over ES Modules Live Bindings. Lint or package boundaries ensure the domain core never imports a UI framework, window, or network SDK.

  1. Module Graph Linking: Because ES Module imports are statically analyzable, build-time linters or package boundaries can enforce an acyclic, inward-only graph where UI components and infrastructure adapters import port interfaces from domain/, never the reverse. TypeScript interfaces erase to zero bytes at emit time.
  2. Composition Root Wiring: At application boot (or route entry), a single composition root instantiates concrete driven adapters (HttpCartAdapter, IndexedDbDraftAdapter) and injects them via closures or factory parameters into domain use cases.
  3. Driving Adapter Invocation: A DOM listener or framework event handler translates UI events into plain command arguments and invokes an inbound port on the main thread.
  4. Domain Evaluation & IC Dispatch: The domain function runs pure JavaScript on the V8 heap with zero DOM retainers. Calling gateway.charge(total, key) hits a monomorphic inline cache in V8 Hidden Classes & IC when production wires one stable adapter shape.
  5. Boundary Translation: The driven adapter serializes the domain object to wire format, executes I/O (fetch, IndexedDB), and runs Runtime Boundary Validation on the response before returning a clean domain result.
TS
// domain/ports.ts & domain/submitOrder.ts (zero UI or fetch imports)
export interface OrderGateway {
  charge(totalCents: number, idempotencyKey: string): Promise<{ receiptId: string }>;
}

export function createSubmitOrder(gateway: OrderGateway) {
  return async (items: readonly { priceCents: number }[], key: string) => {
    const total = items.reduce((sum, item) => sum + item.priceCents, 0);
    if (total <= 0) throw new Error("EMPTY_ORDER");
    return gateway.charge(total, key);
  };
}

Like a wall socket, the domain defines the port geometry so any adapter plugs in without rewiring internal logic. Explicit State Topology Boundaries keep framework stores out of domain closures.

Problem Genealogy#

  • 2005: Alistair Cockburn formalizes Hexagonal Architecture (Ports & Adapters) for backend systems to stop UI and database drivers from entangling core business rules.
  • 2014-2017: Flux, Redux Thunk, and Redux-Saga ship 30-50 KB of middleware that still couples action creators directly to axios, localStorage, and global store shapes.
  • 2019-2022: Business invariants migrate into React custom hooks (useCheckout), forcing teams to boot JSDOM (200-600 ms per suite) and intercept HTTP just to test discount math.
  • 2023-2026: Structural TypeScript ports, zero-dependency domain packages, and boundary parsers decouple core logic from framework churn while keeping Test Fidelity Spectrum trade-offs explicit.

Production Pitfalls#

  • Leaky infrastructure types in port signatures: Symptom: domain unit tests fail in Node.js with ReferenceError: window is not defined (or IDBDatabase is not defined), or replacing axios with fetch breaks 30 domain files. Root cause: outbound ports return SDK error classes, HTTP Response objects, browser DOM/IndexedDB handles, or React Dispatch callbacks instead of plain domain structures. Fix: map SDK errors and wire payloads inside the driven adapter before crossing back into the domain.
  • GC churn and megamorphic dispatch on 60 Hz streams: Symptom: dropped frames (> 16.6 ms) and elevated minor GC time during live WebSocket order-book updates or pointer drags. Root cause: driven adapters allocate fresh validated domain objects on every tick, and passing more than four distinct adapter shapes into the same port call site pushes V8 inline caches megamorphic. Fix: keep high-frequency telemetry outside object-mapping layers and maintain monomorphic production adapter shapes.
  • Monolithic composition root bundle bloat: Symptom: landing-page JavaScript payloads inflate by 80-200 KB with unused payment, IndexedDB, and analytics adapters. Root cause: one top-level composition root statically imports every concrete adapter at module evaluation time. Fix: split composition roots per route and lazy-load heavy driven adapters via dynamic import().

Where this connects

Prerequisites

JS Runtime

ES Modules and Live Bindings

Static module imports make the dependency graph analyzable at build time so lint and package boundaries can keep domain modules free of UI or SDK imports.

Next & related

Mechanical Comparisons