Skip to Content
hono-bento

Handlers

One function per route, in a file named after its operation, typed from its route's contract.

A handler receives the request after authentication and validation, and replies with respond. Declare it with defineHandler, typed from its route's contract:

features/todos/update.ts
import { defineHandler } from 'hono-bento';

import { ownerScope } from '../../access';
import type { Session } from '../../auth';
import type { contracts } from './spec';
import { store } from './store';

// A missing todo, or someone else's, needs no check here: the owner-scoped update matches nothing, Prisma throws, and
// `mapPrismaError` (see app.ts) answers 404.
export const updateTodo = defineHandler<Session, typeof contracts.update>(
  async ({ deps, identity, params, body, respond }) => {
    const { todo, ownerId } = await store.update(deps.db, ownerScope(identity), params.id, body);
    deps.todoChanges.publish({ type: 'updated', ownerId, todo });
    return respond(200, todo);
  }
);

typeof contracts.update gives the handler every argument type from the route, so it restates nothing. The import is type-only, so it creates no runtime cycle with spec.ts.

Arguments

Prop

Type

Checked against the route

route() checks each handler against its route, so a handler can't drift from the spec:

  • its body, query and params types must match the validation schemas' outputs;
  • each respond(status, data) must use a status documented as JSON, with data that matches its schema, and each respond.file(status, ...) a status documented with non-JSON content;
  • on a route that documents responses, it must reply through respond (respond.file or respond.raw included), so context.json() can't bypass the contract;
  • on an allowAnonymous route it must accept a null identity.

When a handler doesn't fit, the error names the problem and shows what the route provides next to what the handler declares:

Type 'RouteHandler<Session, { body: { name: number } }>' is not assignable to type
'HandlerMismatch<"The handler's body type doesn't accept what validation.body produces ...", { title: string }, { name: number }>'.

Files

A status documented with a content other than JSON, such as text/csv or application/pdf, is a file. Send it with respond.file, not respond:

features/todos/spec.ts
export: contract({
  operation: 'export',
  method: 'get',
  path: '/export',
  summary: 'Export todos as CSV',
  auth: { scopes: ['todos.read'] },
  responses: { 200: { description: 'Every todo, as CSV.', content: 'text/csv' } },
}),
features/todos/export.ts
export const exportTodos = defineHandler<Session, typeof contracts.export>(async ({ deps, identity, respond }) => {
  const todos = await store.listAll(deps.db, ownerScope(identity));
  return respond.file(200, toCsv(todos), { filename: 'todos.csv' });
});

respond.file takes a string (sent as UTF-8), bytes, a Blob or File, or a ReadableStream, and sets the headers:

  • Content-Type: the documented content, with ; charset=utf-8 for text sent as a string. Pass contentType to override it.
  • Content-Length: from the body, or from size for a stream.
  • Content-Disposition: given a filename, an attachment the browser saves under that name. Any name is safe, including non-ASCII ones and ones with quotes or line breaks: they're sent as RFC 6266's filename*, with a plain ASCII fallback. Pass disposition: 'inline' to display the file instead.
  • Anything else, such as Cache-Control or ETag, goes in headers.

A content can be a range, such as image/*. The file's type then comes from contentType, or from the Blob's own type, and validateResponses checks that it falls in the range.

Put a route like /export before any /:id route in the spec's routes: routes match in order, so /:id would otherwise take it.

respond(200, data) on a file's status is a type error, and so is respond.file on a JSON status. Range requests and serving a folder of static files aren't covered: use Hono's serveStatic for the runtime, next to mountSpecs.

Any other response

respond.raw(status, response) sends a Response you built yourself, with a documented status. A response that already has that status is sent untouched. It's the escape hatch: nothing checks its body's type.

return respond.raw(200, new Response(xml, { headers: { 'content-type': 'application/xml' } }));

A handler written inline in route({ ... }) gets its types from the route, like one declared with defineHandler.

Errors

Throw an HttpError to send an error response. If the handler validates client input itself, throw HttpError.validation(zodError) for a 400. Anything else that's thrown, including a bare ZodError, becomes a generic 500. See Errors.

Keep handlers thin

A handler translates between HTTP and your domain code. Queries and other logic go in plain functions in the feature folder, such as store.ts, which take what they need (deps.db) as arguments. A background job or another handler can then call the same function. The handler calls it, tells anything else that needs to know (here, the change feed behind the todos stream), and replies:

features/todos/update.ts
export const updateTodo = defineHandler<Session, typeof contracts.update>(
  async ({ deps, identity, params, body, respond }) => {
    const { todo, ownerId } = await store.update(deps.db, ownerScope(identity), params.id, body);
    deps.todoChanges.publish({ type: 'updated', ownerId, todo });
    return respond(200, todo);
  }
);

On this page