Skip to content

    Frontend System Design

    Layered and Clean Architecture for the UI

    Learn layered and clean architecture for front-end apps: UI, application, domain and data layers, the dependency rule, and how to test and enforce it.

    By Published 13 min read

    • frontend-system-design
    • architecture
    • layered-architecture
    • clean-architecture
    Share

    Standard lessonadvancedTypeScript labFrontend System Design

    Before this: Module Boundaries and Public APIs

    What you'll learn: By the end of this lesson you will be able to split a front-end feature into presentation, application, domain and data layers, state the dependency rule and say which way each import may point, decide where state and data fetching belong, write an architecture test that fails when a layer reaches the wrong way, test each layer with the others faked, and judge when this much structure is over-engineering.

    Picture a restaurant. The dining room decides how food is presented to guests, the kitchen decides how a dish is made, the recipe book holds the rules of each dish, and the suppliers deliver ingredients. A guest never walks into the cold store, and a supplier's delivery note never decides the menu. Because each area has one job and the work flows in one direction, you can change a supplier without rewriting a recipe.

    Front-end code often has no walls. A click handler that validates a quantity, calls fetch, shapes the JSON, updates state and picks the error message is a kitchen, a dining room and a loading dock in one room. This lesson puts walls in, and asks when they cost more than they save.

    The running example is a product page with an Add to basket button. The rules: a whole-number quantity of at least 1, no more than the stock, and no more than five of one item (an illustrative rule for the lab).

    The core idea

    1. A layer is a group of modules with one kind of job. This lesson uses four: presentation (what the user sees and does), application (the use cases that orchestrate a task), domain (the business rules, as plain data and pure functions) and data (talking to the network and storage).
    2. The dependency rule says source-code dependencies point one way. Robert C. Martin states it for his concentric circles: dependencies point only inwards, and nothing in an inner circle can name anything in an outer one. Here the inside is the domain and the outside is the framework, the network and the browser.
    3. Inner layers own the interfaces; outer layers implement them. The application declares what it needs (a catalog, a cart store) as interfaces. The data layer implements them. That is the dependency-injection seam from Dependency Injection and Separation of Concerns in the Front End, now applied to the whole feature.

    Three illustrations run through the lesson: a minimal example (the domain rule as a pure function), a realistic example (the full add-to-basket path through four layers) and a failure example (a layer reaching the wrong way, caught by a test).

    Four layers and the direction of arrows

    Martin Fowler describes the common three-way split of an application as presentation logic, domain logic and data access logic, with the presentation depending on the domain logic and the domain logic on the data source. The clean-architecture family goes further: the domain depends on nothing, and the data layer depends on the application's interfaces. Martin's four circles are Entities, Use Cases, Interface Adapters, and Frameworks and Drivers; the mapping to this lesson's names is loose.

    Figure 1. Allowed dependencies in the lab

    Presentation and data depend on the application, the application depends on the domain, and the domain depends on nothingPresentation to Application (calls use cases); Data to Application (implements ports); Application to Domain (uses rules)Presentation: view models, messagesPresentationview models,messagesData: adapters for fetch, storageDataadapters forfetch, storageApplication: use cases and portsApplicationuse cases andportsDomain: rules, pure functionsDomainrules, purefunctionscalls use casesimplements portsuses rules

    How to read this: every arrow points toward the domain. The data layer is drawn on the outside even though the application calls it at run time, because the source-code import points from the data layer to the application's interface.

    In the lab, the domain holds Product, Cart, addLine and totalMinor and imports nothing. The application holds the addToCart use case and the CatalogPort and CartStorePort interfaces and may import the domain. Presentation (presentAddToCart) and data (in-memory implementations of the ports) may import the application and the domain. A composition root, outside the layers, wires them and may import everything.

    Minimal example: the domain rule

    The domain layer is plain data and pure functions. It imports nothing, so it needs no framework, no network and no timers to run. This excerpt is from the lab's domain/cart.ts:

    export function addLine(cart: Cart, product: Product, quantity: number): AddResult {
      if (!Number.isInteger(quantity) || quantity < 1) return { ok: false, reason: { code: "invalid_quantity" } };
      const existing = cart.lines.find((line) => line.productId === product.id);
      const wanted = (existing?.quantity ?? 0) + quantity;
      if (wanted > product.stock) return { ok: false, reason: { code: "out_of_stock", available: product.stock } };
      if (wanted > MAX_PER_LINE) return { ok: false, reason: { code: "line_limit", limit: MAX_PER_LINE } };

    The result is a value, not a thrown exception and not a string for the screen. Money is integer minor units (cents), never a float. The checks run in a fixed order that a test pins down: with stock of 2, asking for 9 reports the stock problem, not the limit.

    Realistic example: one click through four layers

    Figure 2. Add to basket, from click to message

    sequenceDiagram accTitle: One add-to-basket click through the layers accDescr: The view calls a function built by the composition root. The use case asks the catalog port for the product, asks the cart store port for the cart, calls the domain rule, saves a valid cart, and returns a plain result. The presentation function turns the result into a view model with a tone, a message and a badge. participant V as View (button) participant P as Presentation participant U as Use case participant D as Domain rule participant C as Catalog and store ports V->>P: onAddToCart("mug", 2) P->>U: addToCart(productId, quantity) U->>C: getProduct, load C-->>U: product, cart U->>D: addLine(cart, product, 2) D-->>U: ok with new cart, or a reason U->>C: save(cart), only if ok U-->>P: status: added, rejected, unknown or unavailable P-->>V: tone, message, badge

    How to read this: the use case is the only place that sequences the steps. The domain decides, the ports fetch and save, and the presentation function only words the result.

    The use case returns one of four plain statuses: added, rejected (with the domain's reason), unknown_product and unavailable. It catches a failure from the catalog or the store and turns it into unavailable, so the view never needs a try block.

    Martin's article says data crossing a boundary should be simple data structures in the form most convenient for the inner circle: no Response, no framework event, no component.

    The presentation layer here is the framework-free half: presentAddToCart maps each status to { tone, message, badge }. A React component would render that view model and call the handler. The lab has no React in it, so it shows the shape and does not show a component.

    Where state and data fetching live

    "Which layer owns this?" is the question that prevents most muddles. A working rule of thumb, which is a design choice and not a rule of React:

    Kind of thing Lives in Why
    Is the menu open, which tab is selected A component (presentation) Only the view cares
    The cart as a value, and which changes are legal Domain A rule, testable with no framework
    "Load, decide, save" for one user goal Application use case The one place that sequences steps
    The request, its URL, the response format Data adapter The only code that knows the wire

    React's documentation is candid about fetching in Effects: stale responses can arrive out of order, and caching, server rendering and network waterfalls are further non-trivial concerns. It recommends a framework's built-in data fetching where you have one, and otherwise a custom Hook, which makes it easier to adopt a better strategy later and hides the details of an external system so components express intent. In a layered app that Hook is the meeting point: it calls a use case and returns what the component needs, and the component never sees fetch.

    Figure 3. Which layer does this code belong in?

    flowchart TD accTitle: Choosing the layer for a piece of code accDescr: If the code only decides how something looks or reacts to input, it is presentation. If it states a business rule that holds without a screen, it is domain. If it sequences several steps for one user goal, it is an application use case. If it talks to the network, storage or a vendor SDK, it is a data adapter. Q{"What is the code about?"} -->|"how it looks, input handling"| P["Presentation"] Q -->|"a rule true without any screen"| D["Domain"] Q -->|"several steps for one user goal"| A["Application use case"] Q -->|"network, storage, vendor SDK"| X["Data adapter"]

    How to read this: ask what would still be true if the framework were replaced. Rules and sequences survive; rendering and wire formats do not.

    Enforcing the layers with a test

    A diagram on a wiki is not a constraint. Within weeks, one import goes the wrong way "just this once". The lab turns the layering into a test. It lists what each layer may import, reads every source file, and fails if an import points elsewhere:

    const allowed: Record<string, string[]> = {
      domain: [],
      application: ["domain"],
      presentation: ["application", "domain"],
      data: ["application", "domain"],
    };

    A second test confirms every layer has files, so the check is not vacuous, and a third asserts that the domain files contain no import at all. The lab's checker is a few lines of text matching that understands one import form; a real project should use a tool built for the job. dependency-cruiser, for example, is documented as validating a JavaScript or TypeScript project's dependencies against rules you write and reporting violations.

    TypeScript helps in a small way: an import type is guaranteed to be removed from the emitted JavaScript, so a layer can name another layer's types without a runtime dependency. It does not replace the rule, because the architecture test checks the import whether or not it is type-only.

    Failure example: a layer reaches the wrong way

    Suppose someone makes the domain format a message by importing a helper from the presentation folder. The domain now cannot load without presentation code, which may later import a framework. The architecture test fails with a line naming the file and the import (the break-it experiment below shows it). It is cheap to fix in the same pull request as the import.

    Testing each layer on its own

    With the dependency rule in place, each layer is tested with its neighbours faked or absent. The lab has 25 tests in four files. Domain tests call addLine with plain values and need no fakes. Use-case tests use two in-memory adapters and assert outcomes: a rejected request saves nothing, and a catalog or storage failure becomes unavailable. Presentation tests call presentAddToCart with hand-written results. One composition test builds the whole path. This follows Testing Library's principle that the more your tests resemble the way your software is used, the more confidence they can give: narrow, fast tests inside and a few wide ones through the composition root. None of the lab's tests starts a browser.

    The costs, and when this is over-engineering

    Layers are not free. Each one adds files, names and a translation step at every boundary: the domain Product, the use-case result and the view model are three shapes for one idea. Fowler's note on layering says the pattern should be applied at a relatively small granularity: as a system grows, split the top level into domain-oriented modules that are each internally layered. It also says that splitting teams by layer is an anti-pattern, and that data-source substitution, the reason often given for layering, is something he rarely hears of actually happening. Treat the testability and the clarity as the real benefits.

    Layers pay off where rules change often and need tests, and where several entry points share one sequence. They are ceremony for a screen that only shows data (a use case that just forwards a call) and for a prototype whose shape is not yet known. Start with the domain and a use case only where a real rule or sequence exists, and leave plain display components alone. The lesson on feature-based folder structure covers placing layers inside a feature instead of across the app.

    Build it: run the layers and the architecture test

    Goal. Run the layered cart, watch each layer's tests pass, and see the architecture test guard the import directions.

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

    cd examples/frontend
    pnpm install
    cd labs/layered-ui-architecture
    pnpm test           # 25 tests in 4 files
    node src/demo.ts

    Steps.

    1. Run the tests. test/architecture.test.ts holds the three dependency checks; the other three files hold the layer tests.
    2. Run node src/demo.ts. It prints each view model as one line of JSON. The rejected requests leave the stored cart alone, so the saves count is 3, matching the three successful adds; the last request fails because the catalog is switched to failing.

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

    add 2 mugs                       -> {"tone":"success","message":"Added. Cart total EUR 39.98.","badge":2}
    add 1 pen                        -> {"tone":"success","message":"Added. Cart total EUR 42.48.","badge":3}
    add 3 more mugs (5 in all)       -> {"tone":"success","message":"Added. Cart total EUR 102.45.","badge":6}
    add 1 more mug (limit is 5)      -> {"tone":"warning","message":"You can buy at most 5 of one item.","badge":null}
    add 2 more pens (stock is 2)     -> {"tone":"warning","message":"Only 2 in stock.","badge":null}
    add quantity 0                   -> {"tone":"warning","message":"Choose a quantity of 1 or more.","badge":null}
    add an unknown product           -> {"tone":"error","message":"This product is no longer available.","badge":null}
    catalog goes down, add a mug     -> {"tone":"error","message":"We could not reach the shop. Try again.","badge":null}
    saves to the store: 3

    What the lab does not show. No React and no browser, and no HTTP: the data layer is in memory (the next lesson adds a real adapter). The import checker understands one import form and is a teaching tool.

    Break it. In a scratch copy, add import { formatMinor } from "../presentation/present.ts"; to src/domain/cart.ts and run the tests: two architecture tests fail (the layer check, which names the file and the import, and the check that the domain has no imports at all). Delete the line again. Do not commit the experiment.

    Stretch. Add a removeFromCart use case with its domain rule, and extend the architecture test so the presentation layer may not import the data layer directly.

    In practice: a storefront whose rules lived in click handlers

    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 has add-to-basket buttons on the product page, on listing cards and in the account area's re-order list. Each click handler checks stock and the per-item limit slightly differently, and a support ticket says a customer could add six of an item from the listing page while the product page refused. The rule is copied into three components, and two copies disagree.

    Starting architecture

    Figure 4. Starting point: the rule is copied into every handler

    Starting architecture: three click handlers each contain their own copy of the basket rules and call fetchProduct page to Catalog API; Listing card to Catalog API; Re-order button to Catalog APIProduct page: own rule copyProduct pageown rule copyListing card: own rule copyListing cardown rule copyRe-order button: own rule copyRe-orderbuttonown rule copyCatalog API: fetch from each handlerCatalog APIfetch from eachhandler

    How to read this: three places decide the same rule. Fixing one leaves two bugs, and each can only be tested through its component.

    Options considered

    Option What it fixes What it costs Risk
    A shared helper function for the rule One copy of the rule A small module Handlers still fetch and sequence on their own
    Domain rule plus an add-to-basket use case behind ports, with an architecture test One rule, one sequence, testable without a UI Four folders, two interfaces, a composition root Over-structuring the rest of the app

    The decision

    Field Decision record
    Context The same basket rule exists in three handlers and has drifted.
    Decision Move the rule to a pure domain function, add one addToCart use case that returns a plain result, and make all three buttons call it through the composition root. Add an architecture test for import directions. Leave display-only components as they are.
    Consequences, good One rule and one place that sequences steps; each layer testable alone; a new entry point reuses the use case.
    Consequences, bad More files; a view-model mapping to maintain; contributors must learn where things go.
    Revisit when Most use cases only forward a call (the layer is ceremony), or a second team needs different rules. Then split by feature, with layers inside each.

    Rollout and verification

    1. Write the domain tests first, including the order of checks, then the use case with in-memory adapters.
    2. Switch one button at a time, the buggy one first, and compare messages with the old behaviour.
    3. Turn on the architecture test in CI and keep it in the default run.

    The 2 a.m. failure

    A later change imports a price formatter from the presentation folder into a domain function, and is merged on a day when the architecture test was skipped in CI (illustrative). A server-side rendering path that loads the domain without the presentation code's browser-only dependency then fails at import time, and some product pages return errors.

    First three checks: (1) read the stack to find which module failed to load and who imports it; (2) run the architecture test locally; (3) check whether CI skipped it. Mitigation: revert the change. Follow-up: make the test a required check and pass the formatted text in from the presentation layer.

    Architect's notes

    • Draw the arrows before the folders. The first rule worth enforcing is which way imports point.
    • Keep the domain boring: no framework, no I/O, no clock.
    • Return values, not exceptions, across a boundary.
    • Layers inside features, not across the app.
    • Skip the use case when there is nothing to orchestrate.

    Common mistakes

    • Types that mirror the server. The domain then changes whenever the wire format does.
    • React hooks in the domain. The rule can no longer be tested without a renderer.
    • One layer per team. Fowler warns this adds friction.
    • A use case for every button.
    • An unenforced rule. It decays one convenient import at a time.

    Key takeaways

    • Four layers: presentation, application, domain, data, with imports pointing toward the domain.
    • The dependency rule: nothing inside names anything outside. The application owns the interfaces and the data layer implements them.
    • Put rules in pure domain functions, sequences in use cases, wire details in adapters, and how it looks in the view.
    • Return plain results across boundaries so each layer is testable alone.
    • Enforce the directions with a test or a dependency tool, and show that the check can fail.
    • Layers cost translation and files; use them where rules or sequences exist, and inside features rather than across an app.

    Practice exercises

    Exercise 1 - Starter (45 min): Take one click handler in your code that validates, fetches and sets state. List its rules, steps and wire details in three columns and name the layer for each.

    Exercise 2 - Intermediate (2 hours): In the lab, add a removeFromCart domain function and use case with tests at each layer, keeping the architecture test green.

    Exercise 3 - Advanced (half day): Replace the lab's import checker with a rule file for a dependency tool on your own project, and write down one violation it caught or would catch.

    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