@hono-contract/core
v0.2.3
Published
Typed Hono route contracts with Standard Schema validation, OpenAPI, and route source generation
Maintainers
Readme
@hono-contract/core
Define routes as typed objects, check their handlers against those contracts, and generate registrations from .route.ts files.
Install
bun add @hono-contract/core hono hono-openapi zodUse TypeScript with modern module resolution. The source-generation CLI runs with Bun.
Define a contract
Create the owning router:
// src/routes/index.ts
import { createRouter } from "@hono-contract/core"
const router = createRouter()
export { router }Keep each contract and handler in a .route.ts module:
// src/routes/create-user.route.ts
import type { Handler, Route } from "@hono-contract/core"
import { z } from "zod"
import type { router } from "."
const route = {
operationId: "createUser",
method: "post",
path: "/users",
validators: {
json: z.object({ name: z.string(), age: z.coerce.number() }),
},
responses: {
201: z.object({ name: z.string(), age: z.number() }).describe("Created user"),
},
} as const satisfies Route<typeof router>
const handler: Handler<typeof router, typeof route> = (c, respond) => {
const user = c.req.valid("json") // age is a number
return respond(201, user)
}
export default { route, handler }as const satisfies Route<typeof router> checks the contract without widening its path or response statuses. Import the owning router with import type to avoid a runtime dependency cycle.
Handler<typeof router, typeof route> infers the router environment and validated schema outputs, including transforms. respond checks the declared status, representation, and matching response body. A bare schema sends JSON; response schemas are not executed against outgoing values.
These contracts type server handlers; they do not build a Hono RPC client schema.
Response representations
Use a media map when a response sends text, XML, binary data, or another representation. The handler chooses a declared media type explicitly:
const responses = {
200: {
"application/json": z.object({ message: z.string() }).describe("Greeting"),
"text/plain": z.string().describe("Plain text greeting"),
"application/xml": z.string().describe("XML greeting"),
},
204: null,
} as const
// In a handler whose route uses these responses:
return respond(200, "text/plain", "Hello", { Vary: "Accept" })
// Or: return respond(204)JSON and +json media types are serialized as JSON. Other media types send the declared encoded body directly. The schema's output type determines the accepted body, including strings, bytes, and readable streams. Your handler handles content negotiation and produces XML or other encoded formats.
null declares an empty body: call respond(status, headers?). Statuses 204, 205, and 304 require null. This differs from a bare z.null() schema, which sends JSON null.
ContentType builds the same media maps while preserving their literal keys:
import { ContentType } from "@hono-contract/core"
const vendorJson = ContentType.Custom("application/vnd.example+json")
const responses = {
200: {
...vendorJson(z.object({ message: z.string() })),
...ContentType.Text("plain")(z.string()),
},
} as const
// In the typed handler:
return respond(200, vendorJson.type, { message: "Hello" })Builders accept arbitrary subtypes under Application, Text, Image, Audio, Video, Multipart, Font, Message, and Model. Custom accepts the complete media type.
For status-specific methods, createSafeResponder(respond) exposes the same contract as safe[200]("text/plain", "Hello") or safe[204](). Import it from @hono-contract/core and create it inside the handler.
Typed streams
Sequential media accept synchronous or asynchronous item iterables. Use itemSchema to type each item and schema to describe the encoded body:
const updateSchema = z.object({ sequence: z.number(), message: z.string() })
const responses = {
200: ContentType.Application("jsonl")({
schema: z.string().describe("Newline-delimited updates"),
itemSchema: updateSchema,
}),
} as const
async function* updates() {
yield { sequence: 1, message: "Ready" }
}
// In the typed handler:
return respond(200, "application/jsonl", updates())The responder frames items as SSE for text/event-stream, newline-delimited JSON for application/jsonl and application/x-ndjson, or JSON sequences for application/json-seq and application/geo+json-seq. SSE items contain a string data field and optional event, id, and retry fields. A bare schema on these media types also describes each item.
An encoded ReadableStream<Uint8Array> passes through unchanged. Custom streaming formats and multipart/mixed require encoded streams; supply multipart framing and its boundary yourself. Cancelling the response closes an item iterator.
Descriptors require schema, itemSchema, or both. Upstream OpenAPI conversion includes schema; it does not currently emit itemSchema. See the complete SSE and JSONL contracts.
Generate registrations
bunx hono-contract-gen ./src/routesThe CLI updates the root index:
import { createRouter } from "@hono-contract/core"
import createUser from "./create-user.route"
const router = createRouter()
router.implement(createUser)
export { router }This is the same registration as router.implement({ route, handler }). Contracts remain plain objects; no route-builder call is needed.
Add generation and freshness checks to your application:
{
"scripts": {
"routes:generate": "hono-contract-gen ./src/routes",
"routes:check": "hono-contract-gen ./src/routes --check"
}
}--dry/-dprints proposed files without writing them.--checkwrites nothing and exits with code 1 when registrations need updating.--verbose/-vincludes discovery and skipped-file diagnostics.--help/-hshows usage.
The CLI scans .route.ts files recursively without executing them. It accepts default { route, handler } bundles or named route and handler exports. Files without a complete pair are skipped; syntax errors stop generation before files are written.
Missing indexes are created. Nested indexes use scope<typeof parentRouter>(), and parents mount their children. Existing router setup, middleware, and registrations are preserved; repeated runs do not duplicate them.
Updates are additive. After deleting or moving a route, remove its obsolete imports and registrations. Directory names do not add URL prefixes.
Scoped contracts and middleware
Pass your application's environment to createRouter<AppEnv>(). Route handlers then infer that environment through Handler<typeof router, typeof route>.
For a child with additional context, use scope<typeof parentRouter, ChildEnv>(). The child environment must include the parent's. The CLI generates inherited scopes automatically; customize a child index when it needs its own middleware or environment.
Typed middleware uses the same response contract:
import { middleware, type Responses } from "@hono-contract/core"
import { z } from "zod"
import type { AppEnv } from "./env"
const authResponses = {
401: z.object({ error: z.literal("unauthorized") }).describe("Authentication required"),
} satisfies Responses
const authenticate = middleware<AppEnv, typeof authResponses>(authResponses, async (c, next, respond) => {
if (!c.req.header("Authorization")) {
return respond(401, { error: "unauthorized" })
}
await next()
})Pass the response map to middleware so early responses use the same serialization as route handlers. Include ...authResponses in affected route contracts; middleware responses are not merged automatically. Install middleware before implementing or mounting its routes. The generator preserves this setup.
parent.mount(child) mounts the child's registered routes at their declared paths. Implement child routes before mounting them. An optional second onMount argument to createRouter or scope runs after mounting.
See the example's scoped router and typed authentication middleware for a complete setup.
Schema libraries and descriptions
Request and response schemas accept Standard Schema implementations, including Zod and Valibot. You can mix libraries in one contract. Validation and inferred types use the schemas directly; documentation conversion depends on hono-openapi's supported converters.
For Valibot documentation conversion:
bun add valibot @valibot/to-json-schemaAttach descriptions to the schemas themselves: .describe("Created user") with Zod, or v.pipe(schema, v.description("Created user")) with Valibot. The upstream converter preserves schema and field descriptions. The first described representation supplies the OpenAPI response description; each representation keeps its own schema description. Responses without a description use "No description".
Description extraction runs only when generating the OpenAPI document; ordinary API requests do not run it.
router.app exposes the underlying Hono app. Refer to Hono for routing and transport APIs, and hono-openapi for serving or exporting documentation. The example includes an OpenAPI export command.
See the usage example to run the complete workflow.
License
MIT
