--- title: "Ports and adapters" description: "Define dependency ports for Beignet application code so handlers and use cases stay independent from infrastructure." url: "https://www.beignetjs.com/ports" markdown_url: "https://www.beignetjs.com/markdown/ports.md" framework_version: "0.0.65" documentation_scope: "current-checkout" source_revision: "e5b4771b262efbdd036e3a40a514c08d1508316c" source_modified: true --- # Ports and adapters Ports are the dependency interface your application code uses. They keep handlers and use cases independent from infrastructure choices such as databases, caches, mailers, queues, auth systems, and external APIs. For concrete app capabilities, read [Database and transactions](https://www.beignetjs.com/markdown/database.md), [Audit and activity logging](https://www.beignetjs.com/markdown/audit.md), [Cache](https://www.beignetjs.com/markdown/cache.md), [Storage](https://www.beignetjs.com/markdown/storage.md), [Encryption](https://www.beignetjs.com/markdown/encryption.md), [Mail](https://www.beignetjs.com/markdown/mail.md), [Jobs](https://www.beignetjs.com/markdown/jobs.md), [Schedules](https://www.beignetjs.com/markdown/schedules.md), [Authentication](https://www.beignetjs.com/markdown/authentication.md), [Authorization](https://www.beignetjs.com/markdown/authorization.md), and [Rate limiting](https://www.beignetjs.com/markdown/rate-limiting.md). In Beignet apps, `ports/` owns the app-facing types and `infra/` owns concrete implementations. Most apps start with a single `definePorts(...)` object and split port types by feature or capability as the app grows. ```bash bun add @beignet/core ``` ## Define ports Use `definePorts` to capture the exact shape of your dependencies when you wire concrete ports. ```typescript import { definePorts } from "@beignet/core/ports"; type Todo = { id: string; title: string; completed: boolean }; export const initialPorts = definePorts({ todos: { findById: async (id: string): Promise => { return db.todos.findById(id); }, create: async (data: { title: string }): Promise => { return db.todos.create(data); }, }, cache: { get: async (key: string) => redis.get(key), set: async (key: string, value: string, options?: { ttlSeconds?: number }) => { await redis.set(key, value, options?.ttlSeconds); }, delete: async (key: string) => (await redis.del(key)) > 0, has: async (key: string) => (await redis.exists(key)) > 0, remember: async (key: string, factory: () => Promise, options?: { ttlSeconds?: number }) => { const cached = await redis.get(key); if (cached != null) return cached; const value = await factory(); await redis.set(key, value, options?.ttlSeconds); return value; }, }, }); export type AppPorts = typeof initialPorts; ``` Repository ports may also expose purpose-built aggregate methods such as `countByStatus(...)` when a feature needs summary data; see [Aggregates](https://www.beignetjs.com/markdown/database.md#aggregates) for the naming and row-visibility convention. ## Type shape and runtime wiring Canonical apps keep the final dependency type separate from the initial runtime values: | File | Responsibility | | ---------------------- | --------------------------------------------------------------------------------------------------------- | | `ports/index.ts` | Defines `AppPorts` and `AppTransactionPorts`: the completed dependency bag available to application code. | | `infra/port-wiring.ts` | Exports `initialPorts`: app-owned values plus deferred keys that providers must supply during startup. | | `server/providers.ts` | Constructs provider-backed implementations for deferred keys and owns their lifecycle. | TypeScript erases `AppPorts` at runtime, so Beignet cannot discover its keys from the type alone. The `deferred` array materializes those requirements for startup validation. `definePorts()(...)` checks that bound values and deferred names agree with the type; `createServer(...)` then fails boot if a provider leaves any deferred key unresolved. ## Defer ports to providers Production apps usually bind a few app-owned ports directly and let [providers](https://www.beignetjs.com/markdown/providers.md) contribute the rest at server startup. Use the curried `definePorts()(...)` form to declare which keys are deferred instead of writing throwing stub implementations: ```typescript import { definePorts } from "@beignet/core/ports"; import type { AppPorts } from "@/ports"; export const initialPorts = definePorts()({ bound: { gate }, deferred: ["audit", "db", "logger", "mailer", "storage", "uow"], }); ``` Deferred keys boot as marked placeholders. Calling any method on one throws a descriptive error naming the port, and `createServer(...)` validates after provider startup that nothing is left unbound: - The default `onUnboundPorts: "error"` fails boot and lists the unbound keys. - `"warn"` logs the same message and continues. - `"ignore"` skips the check; unbound ports still throw on first use. Tests that boot a server with only the ports they exercise typically use this. ```typescript export const getServer = createNextServerLoader(() => createNextServer({ ports: initialPorts, providers, onUnboundPorts: "error", // default context: appContextBlueprint, }), ); ``` ## Put ports in context The server passes ports into the context factories. From there, use cases, handlers, and hooks receive them through `ctx.ports`. ```typescript import { createNextServer, createNextServerLoader } from "@beignet/next"; import type { AppContext } from "@/app-context"; export const getServer = createNextServerLoader(() => createNextServer({ ports: initialPorts, context: ({ ports, req }) => ({ requestId: req.headers.get("x-request-id") ?? crypto.randomUUID(), ports, }), }), ); ``` ```typescript import { defineRouteGroup } from "@/lib/routes"; import { getTodoUseCase } from "@/features/todos/use-cases"; export const todoRoutes = defineRouteGroup({ name: "todos", routes: [{ contract: getTodo, useCase: getTodoUseCase }], }); ``` ## Use ports in use cases Use cases stay transport-agnostic because they receive the same context shape that route handlers use. ```typescript import { createUseCase } from "@beignet/core/application"; import type { AppContext } from "@/app-context"; const useCase = createUseCase(); const createTodo = useCase .command("todos.create") .input(CreateTodoSchema) .output(TodoSchema) .run(async ({ input, ctx }) => { const todo = await ctx.ports.todos.create(input); await ctx.ports.cache.delete("todos:list"); return todo; }); ``` ## Defer best-effort work Use `BestEffortWorkPort` for follow-up work that may be lost without changing the result of the originating operation. A cache-invalidation broadcast is a good fit when the database remains authoritative and clients reconcile on reconnect: ```typescript import type { BestEffortWorkPort } from "@beignet/core/ports"; export type AppPorts = { bestEffortWork: BestEffortWorkPort; workspaceBroadcast: { publish( workspaceId: string, message: { type: "page.changed"; pageId: string }, ): Promise; }; }; ctx.ports.bestEffortWork.defer(() => ctx.ports.workspaceBroadcast.publish(input.workspaceId, { type: "page.changed", pageId: input.pageId, }), ); ``` In a Next.js app, supply the port from `server/providers.ts` with `createNextBestEffortWorkPort({ defer: after, onError })` on Next.js 15.1 or newer. Defer its key in `infra/port-wiring.ts` and register the adapter after any provider used by the error observer: ```typescript import { createProvider } from "@beignet/core/providers"; import { createNextBestEffortWorkPort } from "@beignet/next"; import { after } from "next/server"; import type { AppPorts } from "@/ports"; const bestEffortWorkProvider = createProvider>()({ name: "next-best-effort-work", setup({ ports }) { return { ports: { bestEffortWork: createNextBestEffortWorkPort({ defer: after, onError: (error) => ports.logger.warn("Best-effort work failed", { error }), }), }, }; }, }); ``` The Next adapter isolates synchronous and asynchronous scheduler failures, callback failures, and error-observer failures from the originating response. That failure boundary is intentional, but it is not durable execution. Use a job or transaction-scoped outbox when work needs retries or must survive process termination. Request deferred work only after the authoritative mutation succeeds, typically from a listener invoked by an after-commit event flush. The Next binding is request-bound: calls from workers, CLI commands, or other contexts unsupported by `after()` report a scheduling failure through `onError` and do not run the callback. ## Unit of work Use a Unit of Work port when a use case needs multiple operations to succeed or fail together. Beignet keeps this as a convention instead of a database abstraction: your app owns the transaction ports, and infra decides how to bind them to Drizzle, Prisma, Kysely, or an in-memory adapter. ```typescript import type { DomainEventRecorderPort, EventBusPort, UnitOfWorkPort, } from "@beignet/core/ports"; type TransactionPorts = { todos: TodoRepository; events: DomainEventRecorderPort; }; export type AppPorts = { todos: TodoRepository; eventBus: EventBusPort; uow: UnitOfWorkPort; }; ``` Use cases call transaction-scoped ports through the callback: ```typescript const todo = await ctx.ports.uow.transaction(async (tx) => { const created = await tx.todos.create(input); await events.record(tx.events, todoCreated, { todoId: created.id }); return created; }); ``` For tests and simple in-memory adapters, use `createNoopUnitOfWork(...)` with a fresh domain-event recorder per transaction: ```typescript import { createDomainEventRecorder, createNoopUnitOfWork, definePorts, } from "@beignet/core/ports"; const todos = createInMemoryTodoRepository(); const eventBus = createMemoryEventBus(); export const initialPorts = definePorts({ todos, eventBus, uow: createNoopUnitOfWork( () => ({ todos, events: createDomainEventRecorder(), }), { afterCommit: (tx) => tx.events.flush(eventBus), afterRollback: (_error, tx) => tx.events.clear(), }, ), }); ``` Production database adapters should replace `createNoopUnitOfWork` with a real transaction wrapper that creates repositories from the transaction client, then flushes recorded events only after commit. Flush validates each payload and publishes its canonical Standard Schema output. Beignet rejects non-JSON output and transforms that change when decoded JSON is validated again. In-process listener registration preserves that state, while serialized transports repeat the check at the receiving boundary. If after-commit flushing fails, the UOW rejects without running rollback hooks because the transaction work already succeeded. That rejection does not mean the database rolled back, so callers must not blindly retry a non-idempotent command. Use a transaction-scoped outbox recorder when follow-up delivery must be durable. Use `createObservedUnitOfWork(...)` when best-effort work should be requested only after the wrapped transaction resolves. Its `afterCommit` observer and optional `onObserverError` callback are isolated, so their failures cannot reject an already committed operation. The observer is a scheduling hook, not durable storage; record durable intent through the transaction-scoped outbox. ## Mock ports in tests Tests can pass plain objects instead of production infrastructure. ```typescript const testPorts = definePorts({ todos: { findById: async (id: string) => ({ id, title: "Test", completed: false }), create: async (data: { title: string }) => ({ id: "1", completed: false, ...data, }), }, cache: { get: async () => null, set: async () => {}, delete: async () => false, has: async () => false, remember: async (_key, factory) => factory(), }, }); ``` ## Shared redaction Ports also provides shared redaction helpers for observability payloads. Use them in audit adapters, provider instrumentation, logging metadata, and devtools custom events when structured details may contain secrets: ```typescript import { redactHeaders, redactValue } from "@beignet/core/ports"; const headers = redactHeaders(req.headers); const metadata = redactValue({ authorization: "Bearer secret", todoId: "todo_1", }); ``` The default redactor hides secret-shaped keys and scrubs high-confidence credential shapes embedded in strings, including authorization schemes, JWTs, credential-bearing URLs, secret assignments, and private keys. App-specific sensitive domain fields should still be handled intentionally before they are logged or stored. ## Ports vs providers Ports are the interface. Providers are startup-time adapters that install ports for production use. Use direct ports when the dependency is simple or test-local. Use providers when the dependency needs configuration, startup, teardown, or reusable packaging.