Skip to Content
hono-bento

Specs

A feature's routing table, the source of truth for its routes and its OpenAPI docs.

A spec describes one feature: where it's mounted and the routes it serves. Declare it with defineSpec(). It takes your identity type from the handlers, and records every route's types, so the app mountSpecs returns works with a typed Hono client.

features/todos/spec.ts
export const contracts = {
  list: contract({
    operation: 'list',
    method: 'get',
    path: '/',
    summary: 'List todos',
    auth: { scopes: ['todos.read'] },
    validation: { query: todoListQuerySchema },
    responses: { 200: { description: 'A list of todos.', schema: todoListSchema } },
  }),
  // create, retrieve, update, delete...
};

export const spec = defineSpec({
  basePath: '/v1/todos',
  name: 'Todos',
  description: 'Create, read, update and delete todos.',
  collection: 'todos',
  model: 'todo',
  routes: [route({ ...contracts.list, handler: listTodos }) /* ... */],
});

Contracts

A route's contract is everything except its handler: method and path, who may call it, what it accepts and what it returns. Declare each with contract(), in a contracts object keyed by operation, so spec.ts reads as the routing table.

Each handler takes its types from its contract (defineHandler<Session, typeof contracts.list>, see Handlers), and route({ ...contract, handler }) joins the two and type-checks that they fit. defineSpec only accepts routes built with route(), so every handler in a spec has been checked.

defineSpec<Session>({ ... }) also works, and gives handlers written inline in the spec their identity type. TypeScript can't infer the rest of a call given a type argument, though, so such a spec records no route types and adds nothing to a typed client. Declare handlers in their own files and leave the type argument out.

Spec fields

Prop

Type

Route fields

A contract has every field below except handler, which route() adds.

Prop

Type

Methods

A route's method is one of get, post, put, patch and delete. The two missing methods are handled for you:

  • HEAD is answered by the route's GET, through the same authentication, validation and handler, with the body left off. The Allow header of a 405 lists HEAD wherever it lists GET.
  • OPTIONS belongs to CORS middleware. Register hono/cors with app.use() before mountSpecs, and it answers preflights before any route runs. Without it, an OPTIONS request gets a 405 listing the allowed methods.

hono-bento add and the example use the usual method for each standard operation: GET to list and retrieve, POST to create, PATCH to update (the body holds only the fields to change) and DELETE to delete. Any other operation is a POST to /:id/<operation>, such as POST /v1/todos/:id/archive.

Mounting

mountSpecs(app, specs, options) mounts each spec at its basePath, with one router per spec. For each route the router runs three steps in order:

  1. Authentication and authorization. Every route, unless it sets allowAnonymous.
  2. Validation, if the route has validation.
  3. The handler.

Before it mounts anything, mountSpecs checks the whole list and throws if:

  • two routes share a method and full path (:id, {todoId} and :id{[0-9]+} count as the same path), or
  • two routes share an operation id.

Either usually means a feature folder was copied without being renamed. It also throws if a route's auth can't work as configured. See Authentication.

Requests that no route matches get the same JSON error shape as every other error: 405 method_not_allowed, with an Allow header, when the path exists under another method, and 404 not_found otherwise. This sets the app's notFound handler; pass handleNotFound: false to keep your own.

To mount a single spec yourself, use createRouter(spec, options) and app.route(spec.basePath, router).

Checking responses

Pass validateResponses: true to mountSpecs to check every response a handler returns against the route's documented responses. Each of these becomes a logged 500:

  • a status the route doesn't document. Errors meant for the caller are thrown as HttpErrors, which aren't checked;
  • a content type other than the documented one (application/json unless the response sets content);
  • a JSON or text body that doesn't match its schema. That includes fields the schema doesn't declare, at any depth (such as data.1.secret), so an internal field can't leak unnoticed. Schemas that allow extra keys, like z.looseObject() and z.record(), keep allowing them.

Routes that document no responses aren't checked.

Every response is parsed, so turn it on in development and tests:

mountSpecs(app, specs, { strategies, authorizer, validateResponses: process.env.NODE_ENV !== 'production' });

Helpers

  • fullPath(spec, route) returns the full path, such as /v1/todos/:id.
  • operationId(spec, route) returns <collection>_<operation>, such as todos_create.

On this page