Skip to content

    Frontend System Design

    Ports and Adapters in the Front End

    Learn ports and adapters in the front end: interfaces the app owns, HTTP and fake adapters, a composition root, and contract tests that keep fakes honest.

    By Published 13 min read

    • frontend-system-design
    • ports-and-adapters
    • architecture
    • contract-testing
    Share

    Standard lessonadvancedTypeScript labFrontend System Design

    Before this: Layered and Clean Architecture for the UI

    What you'll learn: By the end of this lesson you will be able to define a port as an interface the application owns, write an HTTP adapter that translates the server's wire format and failures into the port's terms, write a fake adapter for tests and local work, choose adapters in one composition root, and write a contract test that runs the same checks against every adapter so a drifting fake is caught.

    Think of a travel plug adapter. Your laptop charger has one fixed shape. The wall sockets of different countries have different shapes. You do not rebuild the charger for each country; you carry a small adapter that converts the socket's shape into the one the charger expects. The charger defines what it needs, and the adapter is responsible for the mismatch.

    A front-end app has the same problem with servers, storage and vendor SDKs. If components read title, a string price.amount and stock_on_hand straight from a response, the app has taken the shape of one server. This lesson lets the app define the shape it wants and puts the translation in one small piece of code per outside system.

    The running example is a product page that needs to look up one product by id. The application's word for it is getProduct(id). Behind it can be a real HTTP service or an in-memory fake.

    The core idea

    1. A port is an interface that the application owns. Alistair Cockburn describes a port as identifying a purposeful conversation, with a protocol that takes the form of an API. In the front end, a port is usually a small TypeScript interface such as CatalogPort, written in the application's words.
    2. An adapter implements a port for one technology. Cockburn's article says a technology-specific adapter converts the port's calls into what a particular external device needs, and that the conversation across the API should not change when the technology behind it does. Examples here: an HTTP adapter, an in-memory fake, a localStorage adapter.
    3. The composition root chooses which adapter fills each port. The application never names an adapter. This is the composition root from Dependency Injection and Separation of Concerns in the Front End, which already covers how to hand dependencies in; this lesson is about what makes a good socket and a trustworthy plug.

    This takes the dependency direction of Layered and Clean Architecture for the UI one step further. Cockburn's stated goal is an application that works without either a UI or a database and can be driven by tests as readily as by users.

    Three illustrations run through the lesson: a minimal example (the port and its two adapters), a realistic example (the HTTP adapter translating a server's format and failures) and a failure example (a fake that has drifted from the real adapter).

    The port: written in the application's words

    The port file is the only file the application imports. It says what the application needs and what can go wrong, and nothing about HTTP. This is the lab's catalog.ts, abridged:

    export interface Product {
      id: string;
      name: string;
      priceMinor: number; // integer minor units (cents)
      stock: number;
    }
    
    export type CatalogErrorKind = "unavailable" | "invalid_response";
    
    export interface CatalogPort {
      getProduct(id: string): Promise<Product | null>;
    }

    Three decisions are packed in here, and each is a promise the adapters must keep. Unknown is an answer, not an error: getProduct resolves to null when no product has that id, because an exception is for failure. Failures have the port's own names: an adapter rejects with a CatalogError of kind unavailable or invalid_response, and nothing else. Money is an integer: if the wire format uses something else, the adapter converts.

    A TypeScript implements clause helps a little. The handbook says it checks that a class satisfies an interface and does not change the class's type. It catches a missing method. It does not catch a method that has the right signature and the wrong behaviour, which is where this lesson's contract test comes in.

    Figure 1. The application owns the port; adapters plug into it

    The use case depends on the port; the HTTP adapter and the fake both implement it, and the composition root picks oneUse case to CatalogPort (calls); HttpCatalog to CatalogPort (implements); FakeCatalog to CatalogPort (implements)Use case: loadProductPageUse caseloadProductPageCatalogPort: owned by the appCatalogPortowned by the appHttpCatalog: fetch, DTO mappingHttpCatalogfetch, DTOmappingFakeCatalog: in memoryFakeCatalogin memorycallsimplementsimplements

    How to read this: the use case and both adapters point at the port, and nothing points at an adapter except the composition root (not drawn). Swapping adapters changes no arrow into the use case.

    The HTTP adapter: translation and failure mapping

    The HTTP adapter is the only code that knows the wire. In the lab the stand-in server sends a shape the application does not want: a title, a price as a decimal string inside an object and a snake-case stock_on_hand. This excerpt is from the lab's httpCatalog.ts:

    interface ProductDto {
      id: string;
      title: string;
      price: { amount: string; currency: string };
      stock_on_hand: number;
    }
    
    function minorFromDecimal(amount: string): number {
      if (!/^\d+\.\d{2}$/.test(amount)) throw invalid(`price "${amount}" is not a decimal with two places`);
      return Number(amount.replace(".", ""));
    }

    "19.99" becomes 1999 by string handling only, with no floating-point arithmetic on money. The adapter also validates the body before trusting it: a missing price, a one-decimal price or a negative stock becomes invalid_response, because a response is data from outside the app and is not guaranteed to match the declared type.

    The adapter also has to map HTTP's failure modes onto the port's two kinds. MDN documents that fetch() rejects on a network error or bad scheme, but when the server answers with an error such as 404 it resolves with a Response, so you must check the status yourself. The adapter therefore handles each case:

    try {
      response = await this.#fetch(`${this.#baseUrl}/products/${encodeURIComponent(id)}`, { headers: { accept: "application/json" } });
    } catch (cause) {
      throw new CatalogError("unavailable", "could not reach the catalog", { cause });
    }
    if (response.status === 404) return null;
    if (!response.ok) throw new CatalogError("unavailable", `catalog answered ${response.status}`);

    Figure 2. How each HTTP outcome becomes a port outcome

    flowchart TD accTitle: Mapping HTTP outcomes to the catalog port accDescr: A network error becomes an unavailable error. A 404 becomes null. Any other non-success status becomes an unavailable error. A success status with a body that is not JSON or not the expected shape becomes an invalid response error. A success with a valid body becomes a product. R["fetch(...)"] -->|"rejects"| U1["CatalogError: unavailable"] R -->|"404"| N["null (not found)"] R -->|"other not ok, such as 503"| U2["CatalogError: unavailable"] R -->|"ok, body not JSON or wrong shape"| I["CatalogError: invalid_response"] R -->|"ok, valid body"| P["Product (domain shape)"]

    How to read this: every path ends in one of three port outcomes. The use case never sees a Response, a status code or a DTO.

    Two details matter. The id goes through encodeURIComponent, which per MDN escapes every character except letters, digits and - _ . ! ~ * ' ( ), so a/b?c stays one path segment (the lab requests /products/a%2Fb%3Fc). And the adapter takes fetch as a constructor argument that defaults to the global one, so a test can script any response without a server.

    The fake adapter and the contract

    A fake, in Martin Fowler's vocabulary of test doubles, has a working implementation that takes a shortcut, which makes it unsuitable for production. The lab's FakeCatalog keeps products in a Map, returns null for an unknown id, and has a switch that makes it reject with a CatalogError. Because it implements the port, the same use case runs against it unchanged, in tests and in local development before a backend exists.

    The danger is that a fake is a second implementation, and two implementations drift. Fowler describes contract tests as checks that calls against your test doubles return the same results as a call to the external service would, so a failure signals that the double is out of date. The lab applies the idea in a plain way: one list of checks that every implementation of the port must pass.

    export interface Harness {
      catalog: CatalogPort;
      seed(products: Product[]): void;  // put the backend in a known state
      setDown(down: boolean): void;     // make every request fail, or work again
      close(): Promise<void>;
    }

    Each adapter supplies a harness. For the fake it edits a map; for the HTTP adapter it starts a small local node:http server and points the adapter at it. The six checks cover the port's promises: a known product in the domain's shape, null for an unknown id, exact integer prices (1000 and 5), ids with reserved characters treated as data, unavailable when the backend is down, and recovery afterwards.

    Figure 3. One contract, three subjects

    flowchart LR accTitle: One contract run against three adapters accDescr: A single list of six checks is run against the fake catalog, the HTTP catalog over a local server, and a deliberately drifted fake. The first two pass all six checks. The drifted fake fails two of them. C["Contract: 6 checks"] --> F["FakeCatalog: 6 of 6"] C --> H["HttpCatalog over local HTTP: 6 of 6"] C --> S["SloppyFakeCatalog: 4 of 6"]

    How to read this: passing the same checks is what "interchangeable" means here. The third box is a fake that was drifted on purpose to show the contract can fail.

    Failure example: the drifted fake

    SloppyFakeCatalog looks right: its method has the port's signature, so the compiler accepts it. But it returns undefined for an unknown id (a Map gives undefined for a missing key, and the code casts it) and throws a bare Error when down. Use-case tests written against it would pass and then fail against the real adapter. The contract catches both in the output below: "expected null, got undefined" and "the rejection must be a CatalogError, not a TypeError or a bare Error".

    One honest limit: the lab's "real" adapter talks to a stand-in server the lab wrote, so the contract proves the adapter against that stand-in only. In a project, run the same checks against the real service or a staging copy too, which Fowler says is typically done on the service's own release schedule.

    Switching adapters in the composition root

    The composition root is the one place that may name an adapter. In the lab it is a short function:

    export type CatalogConfig = { kind: "fake"; products: Product[] } | { kind: "http"; baseUrl: string };
    
    export function createCatalog(config: CatalogConfig): CatalogPort {
      if (config.kind === "http") return new HttpCatalog(config.baseUrl);
      const fake = new FakeCatalog();
      fake.seed(config.products);
      return fake;
    }

    Switching from the fake to the real service is a change to the configuration given to this function, not to any use case. Mark Seemann's composition-root rule is that modules are composed in one preferably unique location as close as possible to the application's entry point. An architecture test in the lab enforces it: only the composition root, the test harness and the demo may import from adapters/; the port file and the use case may not, and adapters may not import the use case.

    The lab's use case, loadProductPage, is written once and run against both adapters. It treats a CatalogError as a retryable error view and rethrows anything else: the port promises a CatalogError and nothing else, so a TypeError is a bug in an adapter, and hiding it behind "try again later" would hide the bug.

    When ports are worth it

    A port is a promise you keep for as long as the app lives. Fowler's layering note says the often-cited reason, swapping a data source, is something he rarely hears of actually happening, so do not justify ports with a database swap that never comes. The returns are simpler tests, one place for translation, and a seam for third-party code. They are overhead when a single fetch is used in one place and its shape is already what you want, or when the fake would have to mimic a complex backend and becomes an unverified second system. Keep ports small and in the application's words: a port that mirrors a vendor SDK has a fake as large as the SDK, and the seam protects nothing.

    Build it: run one contract against three adapters

    Goal. Run the six contract checks against the fake and the HTTP adapter, see a drifted fake fail two of them, and see exactly what the HTTP adapter sends.

    Setup. The lab is in the course's example workspace (Node 26.12.1, pnpm).

    cd examples/frontend
    pnpm install
    cd labs/ports-adapters-ui
    pnpm test           # 30 tests in 4 files
    node src/demo.ts

    Steps.

    1. Run the tests. contract.test.ts runs the six checks against both real adapters and expects the drifted fake to fail exactly two; httpAdapter.test.ts covers the wire format; productPage.test.ts runs the use case against both adapters; architecture.test.ts guards who may import adapters.
    2. Run node src/demo.ts and compare with the output below. It starts a real local HTTP server on a free port and never prints the port number. In the last section, a/b?c is requested as /products/a%2Fb%3Fc and an unknown id comes back as null.

    Expected output, captured from a real run (Node 26.12.1, 2026-11-08):

    === FakeCatalog
    PASS 1. returns a known product in the domain's shape
    PASS 2. resolves to null, not undefined and not an error, for an unknown id
    PASS 3. keeps prices as exact integer minor units (1000 and 5, not 999.9999)
    PASS 4. treats ids with reserved characters as data (a/b?c is one id)
    PASS 5. rejects with a CatalogError of kind 'unavailable' when the backend is down
    PASS 6. works again when the backend recovers (no stuck failure state)
    6 of 6 checks passed
    
    === HttpCatalog (real fetch, local HTTP server)
    PASS 1. returns a known product in the domain's shape
    PASS 2. resolves to null, not undefined and not an error, for an unknown id
    PASS 3. keeps prices as exact integer minor units (1000 and 5, not 999.9999)
    PASS 4. treats ids with reserved characters as data (a/b?c is one id)
    PASS 5. rejects with a CatalogError of kind 'unavailable' when the backend is down
    PASS 6. works again when the backend recovers (no stuck failure state)
    6 of 6 checks passed
    
    === SloppyFakeCatalog (drifted on purpose)
    PASS 1. returns a known product in the domain's shape
    FAIL 2. resolves to null, not undefined and not an error, for an unknown id
           expected null, got undefined
    PASS 3. keeps prices as exact integer minor units (1000 and 5, not 999.9999)
    PASS 4. treats ids with reserved characters as data (a/b?c is one id)
    FAIL 5. rejects with a CatalogError of kind 'unavailable' when the backend is down
           the rejection must be a CatalogError, not a TypeError or a bare Error
    PASS 6. works again when the backend recovers (no stuck failure state)
    4 of 6 checks passed
    
    === what the HTTP adapter sent
    {"id":"a/b?c","name":"Odd","priceMinor":100,"stock":1}
    null
    request: GET /products/a%2Fb%3Fc
    request: GET /products/missing

    What the lab does not show. No React and no browser. The HTTP adapter runs against a stand-in server written for the lab, not a real catalog service, so the contract shows consistency with that stand-in only.

    Break it. In a scratch copy, change HttpCatalog to return undefined instead of null on a 404 and run the tests: the contract check for unknown ids fails, and so do two use-case tests that expect not_found. Restore the line and do not commit the experiment.

    Stretch. Add a localStorage adapter for a cart-store port with the same style of contract, using a fake storage object in the harness.

    In practice: a checkout summary built against one pricing service

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A storefront's checkout summary reads prices from a pricing service. Components use the service's field names directly, convert prices with floating-point arithmetic in several places, and tests mock the global fetch in each file. The pricing team announces a new response format, and changing every component would take weeks (illustrative).

    Starting architecture

    Figure 4. Starting point: components know the wire format

    Starting architecture: components read the pricing service's field names and tests mock global fetchSummary to Pricing API; Line items to Pricing APISummary: reads wire fieldsSummaryreads wire fieldsLine items: reads wire fieldsLine itemsreads wire fieldsPricing API: v1 formatPricing APIv1 format

    How to read this: when the service changes its format, every box on the left must change with it.

    Options considered

    Option What it fixes What it costs Risk
    Edit every component for the new format The migration Weeks of changes across the app The next change costs the same
    A PricingPort with an HTTP adapter and a fake, plus a contract test One place for the format; fast tests An interface, two adapters, a harness Port shaped like the service instead of the app

    The decision

    Field Decision record
    Context Components depend on a server's format, so any format change fans out across the app.
    Decision Define a PricingPort in the application's terms (integer minor units, a result for "no price"), write an HTTP adapter that maps both format versions, a fake for tests, and one contract run against both. Choose the adapter in the composition root.
    Consequences, good A format change touches one adapter; tests use the fake and run fast; the contract keeps the fake honest.
    Consequences, bad An extra layer of mapping; the contract and harness must be maintained.
    Revisit when The service adds a feature the port cannot express, or the fake grows large. Then split the port or test against the real service more.

    Rollout and verification

    1. Write the port and the contract first, including down, unknown and invalid-body cases.
    2. Build the adapter for the current format, then move components to the port one at a time and delete the global fetch mocks.
    3. Add the new format to the adapter only, and run the contract again.

    The 2 a.m. failure

    After the migration, a "recently viewed" widget shows "try again later" for products that have no price yet (illustrative). The fake returns null for an unpriced product, but the HTTP adapter's new mapping throws invalid_response when the field is missing. Component tests used the fake and passed, and the contract had no check for "product exists but has no price".

    First three checks: (1) reproduce with a response that lacks the field; (2) compare the fake's and the adapter's behaviour; (3) read the contract for that case. Mitigation: return the port's "no price" result for the missing field. Follow-up: add the missing contract check and run it against both adapters.

    Architect's notes

    • Write the port from the use case's side. Ask what the screen needs, not what the server offers.
    • Write the contract before the second adapter. That is where drift begins.
    • Make failures part of the port, with names, and let adapters reject with those names only.
    • Validate at the edge. A response is untrusted data until the adapter checks it.
    • Rethrow what you do not understand. A bug in an adapter should not look like a network problem.

    Common mistakes

    • A port that mirrors the SDK or the wire format. The seam moves nothing.
    • A fake never checked against the real thing. It passes tests the real adapter fails.
    • Returning undefined, a bare Error or a raw Response through the port. Check the promise in the contract.
    • Naming an adapter outside the composition root.
    • Float arithmetic on money in an adapter.

    Key takeaways

    • A port is an interface the application owns, in its own words and with its own error names.
    • An adapter implements a port for one technology and translates data and failures.
    • A fake is a second implementation that can drift; a contract test runs one list of checks against every adapter, fake included.
    • The composition root is the only place that names an adapter.
    • Fetch resolves on 4xx and 5xx, so an HTTP adapter must check the status and map each outcome.
    • Ports pay for translation and testability, not for a database swap that may never happen.

    Practice exercises

    Exercise 1 - Starter (45 min): Pick one call in your app that uses a server's field names in a component. Write the port, a fake and one test against the fake.

    Exercise 2 - Intermediate (2 hours): Add a seventh contract check in the lab (for example, a product with stock 0 is returned, not treated as missing) and make both real adapters pass it.

    Exercise 3 - Advanced (half day): Add a RetryingCatalog that wraps any CatalogPort, retries unavailable once and never retries invalid_response. Run the contract against it, then add a check that it does not retry a null answer.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments