Skip to Content
hono-bento

API reference

Every export, by entry point.

hono-bento

Specs and handlers

ExportDescription
defineSpec(spec)Declares a feature's spec. Only accepts routes built with route().
contract(contract)Declares a route's contract: everything except its handler.
route({ ...contract, handler })Joins a contract to its handler and type-checks the handler against it.
defineHandler<Identity, typeof contract>(fn)Declares a handler typed from its route's contract.
fullPath(spec, route)The route's full path, such as /v1/todos/:id.
operationId(spec, route)The route's operation id, <collection>_<operation>.

Routing

ExportDescription
mountSpecs(app, specs, options?)Mounts every spec at its basePath, and answers unmatched requests with JSON 404/405. Throws on duplicate routes or operation ids. Returns app, typed with every route for a typed client.
createRouter(spec, options?)Builds a Hono router for one spec, typed with its routes at paths relative to its basePath.
assertUniqueRoutes(specs)The duplicate check mountSpecs runs, on its own.
createAuthMiddleware(requirements, options)The per-route auth middleware, for use outside a spec.
assertAuthConfig(requirements, options)The startup check of a route's auth: unknown strategies, no strategies, scopes without an authorizer.
validate(validation, options?)The per-route validation middleware, for use outside a spec.
toHonoHandler(handler, options?)Adapts a hono-bento handler into a Hono handler.
parseQuery(c)Reads the query string, turning repeated keys into arrays.

CreateRouterOptions<Identity>, accepted by mountSpecs and createRouter (mountSpecs also takes handleNotFound):

Prop

Type

Errors

ExportDescription
HttpErrorThrowable error with type, message, status, code and param. Has unauthorized(), forbidden(), notFound(), invalidRequest() and validation(zodError, part?) helpers.
errorResponseSchemaThe Zod schema of every error body, for clients and tests that parse error responses.
normalizeError(error)Turns any thrown value into an ErrorResponseBody.
mapThrownError(error, mapError)Runs an error through mapError mappers, returning the first HttpError (or undefined).
respondWithError(error, c, options?)Logs and serializes an error into a response.
serializeError(error, c, options?)The body respondWithError would send, as text: how an error that happens mid-stream is sent.
defaultErrorSerializerThe default onError.
STATUS_BY_TYPEDefault status for each error type.
INTERNAL_ERROR_MESSAGEThe message clients see for unexpected errors.

Types

Register, Deps, DepsProvider, ErrorMapper, RouterBaseOptions, DepsOption, OptionsParameter, HandlerOptions, ApiSpec, RouteSpec, Route, RouteContract, AnyRouteContract, CheckedRouteSpec, RouteHandler, HandlerArgs, HandlerArgsFor, HandlerMismatch, RouteArgs, Respond, RespondArgs, Reply, ReplyFor, BodyOf, QueryOf, ParamsOf, ResponsesOf, RawQuery, RawParams, AuthRequirements, RouteValidation, RouteResponse, HttpMethod, MediaType, FileBody, FileSource, FileOptions, StatusesOf, EventsBody, LinesBody, EventStreamWriter, EventOptions, SseOptions, LineStreamWriter, LineSource, SpecVariables, AuthStrategy, Authorizer, AuthMiddlewareOptions, RouteTypes, SpecTypes, SpecSchema, SpecsSchema, MountedSchema, RouterSchema, HonoPath, FullPath, CreateRouterOptions, MountSpecsOptions, ErrorHandlingOptions, ErrorResponseBody, ErrorSerializer, HttpErrorOptions, Logger, RequestPart, ValidationIssue.

hono-bento/openapi

ExportDescription
generateOpenApiDocument(specs, options)One OpenAPI 3.1 document. See OpenAPI.
generateOpenApiDocumentsByGroup(specs, options)One document per spec group.
getObjectSchemaName(spec)The component name of a spec's main object, if it has one.
toSchemaName(model)webhook_endpoint → WebhookEndpoint.

Types

GenerateOpenApiOptions, OpenApiInfo, OpenApiServer, SecuritySchemeObject, OpenApiDocument.

hono-bento/db

Error mappers for the mapError option. They recognize errors by name and code and import no database library. See Database.

ExportMaps
mapPrismaErrorPrisma's P2025 → 404 not_found; P2002 → 409 unique_violation; P2003 → 409 foreign_key_violation.
mapPostgresErrorSQLSTATE 23505 → 409 unique_violation; 23503 → 409 foreign_key_violation; 23502, 22P02 → 400 invalid_request. Looks through cause.

hono-bento/zod

ExportDescription
z (also the default export)Zod, with .openapi() added for names, descriptions and examples.
OpenAPIRegistry, OpenApiGeneratorV31Re-exported from @asteasolutions/zod-to-openapi.

hono-bento/check

The layout, contract and data-access rules, for an app's tests. The hono-bento check command runs the same rules from the command line. It parses source with oxc-parser, an optional peer dependency: install it as a dev dependency. See the layout.

ExportDescription
check(config, { root })Checks the app in root against every rule. Returns the findings: each has a rule, a file and line, and a message saying what to change.
formatFinding(finding)One line per finding: file:line rule: message.
defineConfig(config)Declares hono-bento.config.ts.
RULESEach rule's id and what it checks. hono-bento check --rules prints them.
DEFAULT_DRIVERSThe database drivers and ORMs that features may not import, unless db.drivers says otherwise.

Types

CheckConfig, CheckOptions, Finding, RuleId.

The hono-bento command

CommandDescription
hono-bento init [dir]Writes a new app in the layout.
hono-bento add featureAdds a feature: its schemas, its folder and its line in specs.ts.
hono-bento add endpointAdds a route to a feature: its contract, route, handler and test.
hono-bento checkChecks the app in this folder against every rule.

The CLI covers each command's options and what it writes.

hono-bento/testing

Tests generated from an app's specs, with fast-check (an optional peer dependency). See Verification.

ExportDescription
fuzzSpecs(app, specs, options)Sends every route requests generated from its contract and returns each invariant that didn't hold, shrunk to the smallest request: no 5xx for valid input, the standard error shape, 401 without credentials, 400 for invalid input, 405 for other methods.
formatFuzzFailure(failure)A failure as readable lines, with the request that replays it.
validInput(schema)A fast-check arbitrary of values a client could send that schema accepts.
invalidInput(schema)An arbitrary of values schema rejects: the wrong type, an extra key, or one field of the wrong type.
fromJsonSchema(schema)An arbitrary for a JSON Schema, which validInput builds on.

Types

FuzzOptions, FuzzFailure, RequestTarget.

On this page