Engineering

Which architecture helps LLMs find their way? Hexagonal, adapted to a functional Next.js codebase

Ports and adapters were written for objects. How we keep them in a Next.js codebase mostly written by agents, in seven files per feature and rules written with their reason.

A person and a small round robot drawing the floor plan of a building together at a drafting table, in a sunny studio.

What the book says

Cockburn sets a goal: an application should be drivable by a user, a program, an automated test or a script alike, and be developed and tested without its real database or devices. For that, the application exposes ports, one per conversation with the outside (save a user, send an email), and one or more adapters plug into each port (a PostgreSQL database or an in-memory one for tests, an email provider or a fake mailbox).

In the examples that circulate, written in object-oriented style, the port is an interface and the service receives it in its constructor:

interface UserRepository {
  save(user: User): Promise<void>
}

class UserService {
  constructor(private repo: UserRepository) {}
}

Carried over as is into a TypeScript front end, this arrangement gives less than it seems to, for four reasons:

  • Everything around it is a function. Nothing stops you from writing class UserService in JavaScript. But React has recommended function components over classes since Hooks (16.8, February 2019), and in Next.js a Server Component, a Server Action or a 'use cache' function are functions, async for the last two. Using OOP there would be odd.
  • The interface exists only at compile time. TypeScript compares the shape of objects, not their name: any object with a save method passes for a UserRepository. With const repo = { save: async () => {}, anything: 1 }, the call new UserService(repo) compiles. At run time nothing of the interface is left. The only real contract is the signature of the save function, and an exported function gives exactly the same one.
  • The full textbook version multiplies files. Marking a to-do as important touches five files in a Next.js application laid out like the book: the application service, the inbound port, the outbound port, the repository adapter and the route. The framework’s own way does it in one.
  • Classes and the container suffer from circular imports. In those examples the entity emits domain events, and the events module imports the entity back. With JavaScript modules, when A imports B and B imports A, one of the two runs before the other is ready, and a value read at that moment is not initialised yet: an error with ES modules, undefined in CommonJS. This hits what runs at load time, a class extending another or a container instantiating everything at start-up, not a function called later.

Three correspondences

A function import is analogous to an injection.

// services/userService.ts
import { sendEmail } from './adapters/sendEmailPostmark'
// swap for './adapters/sendEmailSES'

export async function invite(user: User) {
  await sendEmail({ to: user.email })
}

// userService.test.ts
vi.mock('./adapters/sendEmailPostmark', () => ({ sendEmail: vi.fn() }))

The dependency is explicit at the top of the file. Swapping an implementation is a one-line change; a test replaces the module. There is no container, and nothing to register.

A function’s signature is close to a port.

// adapters/saveUser.ts
export async function saveUser(u: User): Promise<void>

// adapters/publishEvent.ts
export async function publishEvent(e: DomainEvent): Promise<void>

// services/userService.ts
import { saveUser } from '../adapters/saveUser'
import { publishEvent } from '../adapters/publishEvent'

export async function createUser(input: CreateUserInput) {
  const user = { id: crypto.randomUUID(), ...input }
  await saveUser(user)
  await publishEvent({ type: 'UserCreated', userId: user.id })
  return user
}

The parameter and return types are the contract, checked where the function is called. No class implements anything.

The module stands in for the singleton.

// db.ts: one instance, shared by every import
export const db = createDbClient()

One instance per module graph, not per application: the server bundle and the client bundle, hot reloading in development and each serverless instance each have their own.

Seven files per feature

app/[workspace]/projects/
├── _components/        the UI, client side
│   ├── ProjectList.tsx
│   └── NewProjectDialog.tsx
├── _lib/
│   ├── types.ts        data contracts
│   ├── schema.ts       form validation, client and server
│   ├── validators.ts   business rules, server only
│   ├── services.ts     the only database access
│   ├── loaders.ts      reads and transformation
│   ├── actions.ts      writes
│   └── utils/          optional: pure helpers shared by several files
├── layout.tsx
└── page.tsx            the entry point, server side

Component files are named after the component; every other file is lowercase. A reviewer, or an agent, knows what a file may contain from its name before opening it.

The rules file by file

This is our architecture document, with the product’s names removed. Each rule is followed by why it exists, because the reason is what lets a rule be applied to a case it did not foresee.

types.ts: the data contracts. Only type definitions, no logic. Use the types generated from the database schema before introducing a hand-written shape: a hand-written shape drifts from the table the day someone adds a column.

schema.ts: the validation schemas. Zod schemas for the forms, used on the client and on the server, kept next to the forms they validate. If the schema is written in two places, the two versions drift apart within a month.

validators.ts: the business rules. Server-only (import 'server-only' at the top). The rules that need data or a permission: an email must be unique, the user must hold a right on the workspace. They throw a descriptive error, and an action calls them before it writes. If the rule is written in a form handler, the next form forgets it; in a validator it exists in one place and every action calls it.

services.ts: the database access. Server-only, and the sole importer of any database client, privileged or not. Pure data access: no business logic, raw rows returned for the loaders to shape, an exception thrown on a database error. A service may import a pure helper from utils/. Changing the client, or the vendor, changes one file per feature, and a query that looks wrong is found in one place. The privileged client sees every workspace, so a service never decides who may call it: the validators do, before.

loaders.ts: reads and transformation. Server-only. Split in two: a private cached core, pure data by arguments, and a public uncached wrapper that gets the user, checks the permission, then calls the core. All transformation (computations, formatting, aggregation) happens inside the core, once, cached. Parallel reads use Promise.all. Never a permission check inside the cached core, for three reasons: on a cache hit the body is skipped, so a check inside runs only on a miss; a cached function cannot read request data (cookies, headers, session), so a call to get the user fails or returns nothing; and the cache key is the arguments, so unless the user’s identity is an argument, one user’s result is served to the next. Cache granularity: a cache with a long life and per-argument keys makes one immortal entry per distinct argument, so user input (a search string, a cursor) never goes straight into the arguments of a long-lived cached function; cache the canonical read and filter outside the cache boundary, in the wrapper.

actions.ts: the writes. 'use server' at the top. Every action goes through the authenticated action client with an input schema, so a thrown error is routed once, with no ad-hoc try/catch. The order is fixed: validate (the validators, which run the permission check), mutate (the services), invalidate the cache. The action returns the same shape every time. A session is not enough: the action client proves the caller is signed in, the validator proves the caller may act on this workspace, and every id in the payload is bound to that workspace before the privileged client is built.

Which invalidation to call, and why:

CallWhereWhy
updateTag(tag)server actionsread-your-own-writes: the user who wrote sees fresh data on the next read
an immediate expiry of the tag (expire: 0)route handlers, every mobile writethe same immediacy from a context where updateTag refuses to run: it throws for a caller whose page ends in /route, after the row is written, which looks like a failed save
revalidateTag(tag, profile)webhooks, external eventsstale-while-revalidate: nobody is waiting for the fresh read, one stale read is fine
revalidatePath(path)admin bulk operations onlyempties the whole route at once, so reserved for administration operations
refresh()actions that write data read without a cachereleases the client router cache so screens already open re-read

A profile passed to revalidateTag to “fix” the route-handler case makes it stale-while-revalidate, so the next read still serves the pre-write entry: the fix is the immediate expiry, not the profile.

_components/: the interface. 'use client' at the top. Components receive transformed data through props and never manipulate it: no computation, no formatting. Forms use the form library with the Zod schema and derive their submit state from it; local state is limited to what the UI needs. Mutations call the server actions. If a component formats a date, the next one will format it differently; if a component holds a business rule, the validators do not see it.

page.tsx: the entry point. A server component with no client directive. It calls the loaders, in parallel, passes the data as props, renders, and declares its metadata, and that is all it contains.

utils/: optional. Pure functions only, no side effects, no database, documented, grouped by domain. Created when a helper is used by several files or is complex enough to test on its own; otherwise the helper stays private in the file that uses it, next to its use.

The document’s anti-patterns

  • Data transformation in a component.
  • Database access outside services.ts.
  • Business logic in a component.
  • Several cache revalidations scattered in a mutation, with no one knowing what needs updating.

What a machine checks

Four of the rules are checked by semgrep on every merge request, each with its reason in the error message: an export from a file marked 'use server' must be an action; the privileged client is never built at module scope; no permission check inside a 'use cache' function; an action that builds the privileged client must have called the permission check first. Two tests block the pipeline: one follows every action to the services it calls and refuses a privileged query without an authorisation on its path; the other refuses an action that writes data and calls none of the invalidations. The date rules (no timezone-naive getters outside one helper module) live in a lint plugin.

The concepts of hexagonal architecture we deliberately set aside

We deliberately set aside factories, classes everywhere, circular dependencies and layers that exist only for form’s sake. We kept the business rules in one place, contracts expressed as types, boundaries that can be tested by replacing a module, and one role per file. The rules, in the validators, do not depend on the framework; the orchestration, in the loaders and the actions, is written in Next.js vocabulary, and that is a choice: isolating it too would have been a layer for its own sake.

Why this helps a model and a human

A coding agent reads the repository instructions, then the architecture document, then the feature folder. If the layout is the same everywhere, the document is one page, and a file name tells the agent what the file is allowed to contain. The rules are written as sentences with a reason, because an agent that knows why a rule exists applies it to the case the rule did not foresee: the table above is the example, a route handler is not an action, and the reason says which call to make.

The human gets the same thing. Reviewing a merge request on a feature means opening actions.ts and services.ts, or loaders.ts, and knowing in advance what each may contain. A folder generated entirely by a model is readable the day after, because it has the same shape as the one written by hand the month before.

The original article: Alistair Cockburn, Hexagonal architecture, 2005.

Back to the light read (2 min).

Related articles