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
Hexagonal Command Flow & Adapter Swap
Trace a checkout command across driving adapter, pure domain core, and swappable driven adapters without inverting dependency direction.
At boot, the composition root injects a concrete OrderGateway adapter (HttpOrderAdapter in prod, InMemoryOrderAdapter in tests) into the domain factory.
const submitOrder = createSubmitOrder(httpOrderAdapter);- dependencyDirection
- outer -> inner
- domainImports
- []
- wiredAdapter
- HttpOrderAdapter
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.
- 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. - 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. - 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.
- 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. - 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.
// 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(orIDBDatabase is not defined), or replacingaxioswithfetchbreaks 30 domain files. Root cause: outbound ports return SDK error classes, HTTPResponseobjects, browser DOM/IndexedDB handles, or ReactDispatchcallbacks 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
Runtime Boundary Validation (Parse, Don't Validate)
Driven adapters must validate untrusted wire payloads at the boundary before constructing domain entities.
Client State Topology: Ephemeral, URL, Server Cache & Persistent
Defines where pure domain state ends and server-cache or ephemeral UI state begins across application layers.
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
Test Fidelity Spectrum: Unit, Component, Browser & E2E
Swapping driven adapters with in-memory fakes shifts domain tests from slow E2E runs to millisecond unit checks.
Mechanical Comparisons
- Contrasts WithHexagonal Architecture (Ports & Adapters) in Frontend Applications vs Test Fidelity Spectrum: Unit, Component, Browser & E2E
Swapping driven adapters with in-memory fakes shifts domain tests from slow E2E runs to millisecond unit checks.