What is Clean Architecture?
Related reading: DDD in frontend
The dependency rule concerns source code: dependencies point toward inner policies. Domain models express business rules, use cases coordinate operations, adapters translate data, and frameworks and infrastructure sit outside. Four physical folders are not mandatory. [1][3]
Control may flow outward when a use case reads a price through a port, yet the inner code never imports the HTTP implementation. DDD helps discover domain models and boundaries, while hexagonal architecture emphasizes ports and adapters; these approaches can complement one another. [2]
Domain model: a framework-free quotation
domain/quote.ts
export interface Quote {
readonly quantity: number;
readonly totalCents: number;
}
export function requireQuantity(quantity: number): void {
if (!Number.isSafeInteger(quantity)) {
throw new RangeError("Quantity must be a safe integer.");
}
if (quantity < 1) {
throw new RangeError("Quantity must be positive.");
}
}
export function requireUnitPrice(unitPriceCents: number): void {
if (!Number.isSafeInteger(unitPriceCents)) {
throw new RangeError("Price must be a safe integer.");
}
if (unitPriceCents < 0) {
throw new RangeError("Price cannot be negative.");
}
}
export function calculateQuote(
quantity: number,
unitPriceCents: number,
): Quote {
requireQuantity(quantity);
requireUnitPrice(unitPriceCents);
const totalCents = quantity * unitPriceCents;
if (!Number.isSafeInteger(totalCents)) {
throw new RangeError("Total exceeds the safe integer range.");
}
return { quantity, totalCents };
}
The example assumes EUR, whole-item quantities and a unit price in cents. calculateQuote rejects negative prices, fractional quantities and totals outside the safe integer range. Zero-priced items are allowed. The calculation is deterministic and requires no network.
Multiple currencies, tax and rounding need a separate model; this is not a complete financial engine. A client-side quote is not authoritative: the backend must recalculate and validate the order. Never rely solely on browser-side enforcement of security-sensitive rules.
Use case and dependency inversion
application/create-quote.ts
import { calculateQuote, requireQuantity } from "../domain/quote.js";
import type { Quote } from "../domain/quote.js";
export interface PriceReader {
readUnitPrice(signal?: AbortSignal): Promise<number>;
}
export function createQuoteUseCase(priceReader: PriceReader) {
return async function createQuote(
quantity: number,
signal?: AbortSignal,
): Promise<Quote> {
requireQuantity(quantity);
signal?.throwIfAborted();
const unitPriceCents = await priceReader.readUnitPrice(signal);
signal?.throwIfAborted();
return calculateQuote(quantity, unitPriceCents);
};
}
The createQuote use case validates quantity, obtains a price through PriceReader and delegates arithmetic to the domain. The port expresses the application's need rather than the entire REST interface. Passing the implementation as a function argument is sufficient; a DI container is optional. [1][2]
AbortSignal propagates cancellation to the adapter and lets the use case discard a result even if the port completes after cancellation. This is a deliberate dependency on a standard platform API, not full platform independence. Define a small cancellation contract of your own if the core must run without this API. [6]
HTTP adapter and runtime validation
infrastructure/http-price-reader.ts
import type { PriceReader } from "../application/create-quote.js";
import { requireUnitPrice } from "../domain/quote.js";
function readPriceField(data: unknown): number {
if (data === null) {
throw new TypeError("Missing price response.");
}
if (typeof data !== "object") {
throw new TypeError("Expected a price object.");
}
if (!("unitPriceCents" in data)) {
throw new TypeError("Missing unit price.");
}
const { unitPriceCents } = data;
if (typeof unitPriceCents !== "number") {
throw new TypeError("Expected a numeric price.");
}
requireUnitPrice(unitPriceCents);
return unitPriceCents;
}
export function createHttpPriceReader(
endpoint: URL,
request: typeof fetch = fetch,
): PriceReader {
return {
async readUnitPrice(signal?: AbortSignal): Promise<number> {
const response = await request(endpoint, { signal });
if (!response.ok) {
throw new Error(`Price request failed: ${response.status}`);
}
const data: unknown = await response.json();
return readPriceField(data);
},
};
}
Treat JSON as unknown. The adapter checks the HTTP status, the presence of unitPriceCents, its numeric type and the price invariant through sequential guard clauses. Static types do not validate external input; fetch does not automatically reject HTTP 4xx or 5xx responses. [4][5]
The adapter does not expose Response to the use case. Network failure, malformed JSON and an invalid price terminate the operation. The UI should translate errors into understandable messages instead of exposing raw exceptions. Consider bounded retries for GET, but never conceal contract violations or cancellation.
Presentation and composition root
presentation/quote-presenter.ts
import type { Quote } from "../domain/quote.js";
const MAX_DISPLAY_CENTS = 1_000_000_000_000;
export function formatQuote(quote: Quote, locale: string): string {
if (quote.totalCents > MAX_DISPLAY_CENTS) {
throw new RangeError("Amount exceeds supported display range.");
}
const formatter = new Intl.NumberFormat(locale, {
style: "currency",
currency: "EUR",
});
return formatter.format(quote.totalCents / 100);
}composition.ts
import { createQuoteUseCase } from "./application/create-quote.js";
import { createHttpPriceReader } from "./infrastructure/http-price-reader.js";
export function composeQuoteFeature(endpoint: URL) {
const priceReader = createHttpPriceReader(endpoint);
return createQuoteUseCase(priceReader);
}
The presenter formats a monetary amount for the user's locale without changing the domain value. Dividing by 100 is for EUR display only; very large amounts need a separate precision strategy. The composition root chooses the concrete adapter using an endpoint provided by configuration. The example limits displayed amounts to 1,000,000,000,000 cents; larger values are explicitly rejected.
React, Angular or plain DOM code can invoke the same createQuote function. Loading state, error display and cancellation of a previous request belong to the UI. With overlapping requests, publish only the current request's result. The example includes a core, adapter and presenter, not a complete UI component.
Testing with Given-When-Then
quote-gwt.test.cjs
const { test } = require("node:test");
const assert = require("node:assert/strict");
const { calculateQuote } = require("./dist/domain/quote.js");
const {
createQuoteUseCase,
} = require("./dist/application/create-quote.js");
test("calculates a quote in minor units", () => {
// Given
const quantity = 3;
const unitPriceCents = 125;
// When
const quote = calculateQuote(quantity, unitPriceCents);
// Then
assert.deepEqual(quote, { quantity: 3, totalCents: 375 });
});
test("use case works with an in-memory port", async () => {
// Given
const createQuote = createQuoteUseCase({
readUnitPrice: async () => 125,
});
// When
const quote = await createQuote(3);
// Then
assert.equal(quote.totalCents, 375);
});
A domain test checks arithmetic without an API; a use-case test injects a controlled port implementation. Adapter tests simulate HTTP responses by injecting a fetch function. The suite also covers invalid prices, overflow, cancellation and 503 responses. [7]
Given describes the initial state, When performs the operation, Then checks the outcome. It is a useful test structure, not a requirement to use Cucumber. Simulated transport cannot establish compatibility with the actual backend: also test contracts, integration and critical user journeys.
Module boundaries and CI enforcement
tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": [
"ES2022",
"DOM"
],
"strict": true,
"noUncheckedIndexedAccess": true,
"outDir": "dist",
"rootDir": ".",
"noEmitOnError": true
},
"include": [
"domain/**/*.ts",
"application/**/*.ts",
"infrastructure/**/*.ts",
"composition.ts",
"presentation/**/*.ts"
]
}Related reading: Monorepo vs Multirepo
Related reading: TypeScript configuration
In the example, domain imports neither application nor infrastructure; application may import domain, infrastructure implements the application port, and presentation consumes the domain model. Only composition.ts wires the implementation to the use case. In larger systems, group layers by business feature rather than one global services directory.
TypeScript strict does not enforce import direction on its own. Add lint rules or Nx module boundaries and run them in CI. Prevent cycles and imports into other modules' private internals; test allowed dependencies as well. Separate packages or Project References can support isolation but are not mandatory. [8]
When to use it and how to migrate
In a small CRUD screen, a port for every function may merely increase file count. The benefits grow with nontrivial rules, multiple interfaces or changing data sources. Evaluate test cost, change frequency and the number of places where logic is duplicated.
Do not rewrite the entire project at once. Choose one use case, protect existing behavior with tests, extract pure rules and replace its HTTP dependency with a port. Check whether an API change really remains confined to the adapter. If an abstraction provides neither isolation nor simpler tests, simplify it.
