Hi all, I love Hono and everything it has to offer. Its type safety, performance, and syntax is beautiful. However, I felt it had some areas that it was lacking as far as how it would fit inside enterprise-level software.
Due to this, our team created `hono-typed-router.` It is a thin layer on top of `hono` \+ `zod-openapi` that focuses on fixing one issue: **inheritance** and **context.**
With \`hono-typed-router\`, everything is based around inheritance and context. You always define child routes off a parent's type definition. The parent's middleware, bindings, etc. are always available in the child. Its syntax and usage also promote directory structures that simulate route structures (*think file-based routing*). It was also created to work as closely as possible to native Hono, so you can still leverage the full power of the web server.
**It’s also built around OpenAPI.** Every route is a `hono`, `zod-openapi` route, so you get a full spec for free, and the library works to keep that spec honest:
* Path params are inferred from the inherited path, so they’re typed, validated, and documented without re-declaring them at each level.
* Shared responses (401/403/422), security, and tags live in `routeDefaults` and merge into every route.
* Error handlers are type-checked against the route’s declared responses. Return a 409 you didn’t document, and it won’t compile.
* Scope checks are driven by each route’s `security` field, so the docs and the enforcement can’t disagree.
It also catches things Hono silently accepts: a `/:id` router shadowing a `/stats` sibling, duplicate routes, or a child mounted somewhere that skips its parent’s auth middleware. All of these throw at startup.
And it’s cheap: we measured about 2% type-checking overhead over plain zod-openapi, enforced by a type budget in CI.
We've had a great time using it over the past year or so and we'd love to share it with you all. Hopefully you find it useful.
Repository: [https://github.com/cristianhg2/hono-typed-router](https://github.com/cristianhg2/hono-typed-router)
Here is an example usage:
import { z } from 'zod';
import { testClient } from 'hono/testing';
import {
createRouter, defineChildContext, defineRootContext, handle,
jsonRequest, jsonResponse, matchErrors, mountRouter,
} from 'hono-typed-router';
import { createScopeMiddleware } from 'hono-typed-router/scopes';
const Project = z.object({ id: z.string(), name: z.string() });
const ErrorBody = z.object({ message: z.string() });
// 1. Root context: every route below gets a typed `c.var.session`
const api = defineRootContext('/api').middleware<{ session: Session }>(async (c, next) => {
c.set('session', await readSession(c.req.header('authorization')));
await next();
});
// 2. Children inherit the path AND the vars. `.bind()` loads the org or 404s.
const org = defineChildContext(api, '/orgs/:orgId').bind('org', 'orgId', (id, c) =>
findOrg(id, c.var.session.userId),
);
const projects = defineChildContext(org, '/projects');
// 3. Shared OpenAPI responses + scope enforcement, declared once for every route
const makeRouter = createRouter({
routeDefaults: {
responses: {
401: jsonResponse(ErrorBody, 'Unauthorized'),
404: jsonResponse(ErrorBody, 'Not found'),
},
},
routeMiddleware: createScopeMiddleware(api, { resolve: (c) => c.var.session.scopes }),
});
const projectsRouter = makeRouter(
projects,
({ app, defineRoute }) => app.openapi(defineRoute('post', {
security: [{ bearer: ['projects:write'] }], // documented AND enforced (403)
request: jsonRequest(z.object({ name: z.string().min(1) }), 'New project'),
responses: {
201: jsonResponse(Project, 'Created'),
409: jsonResponse(ErrorBody, 'Slug taken'), // remove this and the arm below won't compile
},
}), (c) =>
handle(
c,
async ({ param, json }) => {
param.orgId; // string: inferred from '/api/orgs/:orgId/projects', never declared
c.var.session; // inherited from the root
return c.json(await createProject(c.var.org.id, json.name), 201); // c.var.org from .bind()
},
matchErrors([SlugTaken], {
SlugTaken: (_e, c) => c.json({ message: 'Name already taken' }, 409),
}),
),
)
);
const orgRouter = makeRouter(org, () => {}, [projectsRouter]);
const app = mountRouter(api, [orgRouter]);
// 4. End-to-end typed client: path, params, body, and every response status
const client = testClient(app);
await client.api.orgs[':orgId'].projects.$post({
param: { orgId: 'acme' },
json: { name: 'Website' },
});