Hono is the web framework we use when an API has to be small, typed and portable. A boundary first: our measured production use is an API on Node, an adapter inside another framework, and plain Fetch-handler Workers that share one Request and Response model. We have not deployed a Worker built on the framework in the work this post draws on, so the Workers sections rest on its documentation and say so. This is part of the edge-infrastructure group that the WordPress to Workers migration anchors.
What kind of framework is it?
It is a web framework built on Web Standards. Its documentation says it relies only on the Fetch API’s Request and Response, plus URL and Headers, so the same code runs on any runtime that supports them (Hono web standards). The listed targets include Cloudflare Workers, Deno, Bun, Fastly Compute, AWS Lambda, Vercel and Node.js through an adapter.
That portability is the reason to choose it over a Node-only framework when an edge deployment is plausible. A handler is a function from a request to a response, and middleware wraps it. There is no framework-specific request object to untangle when the code moves from a server to a Worker.
How does Hono compare with Express?
Hono is smaller and Fetch-native; Express is older and Node-native. The routing difference is documented: Hono’s default SmartRouter chooses between RegExpRouter, which compiles all routes into one regular expression, and TrieRouter, which the documentation describes as slower than the first but much faster than the Express router and supporting all patterns (Hono routers). We did not benchmark the two against each other, so we do not quote speedups.
| Hono | Express | |
|---|---|---|
| Request model | Web Standard Request and Response |
Node IncomingMessage and ServerResponse |
| Runs on Workers | Yes, as the default export | Not directly, it needs Node APIs |
| Runs on Node | Yes, through an adapter | Yes, natively |
| Typed context | Variables and module augmentation |
Add your own types |
| Validation | Thin built-in, Zod and Standard Schema packages | Third-party |
| Ecosystem age | Newer, smaller | Large, long-established |
Which should you choose? Hono if the API might run on an edge runtime, or you want a typed context without ceremony. Express if you depend on a Node-only middleware that has no Fetch equivalent. Hono’s Node adapter means starting on Node does not close the door to Workers later.
How do you structure a Hono API for production?
Build the app in a factory function that takes its dependencies, mounts route modules, and returns the app. The production API we run exports createApp(deps, options), which creates a Hono instance, registers global middleware, and mounts 14 route modules with app.route("/api/<name>", routes(deps)) (from the repository).
The skeleton, generic:
import { Hono } from 'hono';
import { secureHeaders } from 'hono/secure-headers';
export function createApp(deps: AppDeps): Hono {
const app = new Hono();
app.use('*', secureHeaders());
app.get('/healthz', healthHandler(deps));
app.route('/api/auth', authRoutes(deps)); // before the guard: login needs no session
app.use('/api/*', apiAuth(deps.config)); // then everything under /api is guarded
app.use('/api/*', csrfGuard());
app.route('/api/items', itemsRoutes(deps));
app.route('/api/runs', runsRoutes(deps));
app.notFound((c) => c.json({ error: { code: 'not_found', message: 'Route not found' } }, 404));
app.onError(errorHandler);
return app;
}
Three decisions in that skeleton carry the design:
- Dependencies are arguments, not imports. Route modules receive
deps(database, config, queue), so a test can pass fakes and the same app can be built differently per environment. - Order is the security model. The login routes mount before the auth guard because they must be reachable without a session. Everything under
/api/*mounts after it. Moving one line changes who can reach what. - One entry point builds the app, another serves it. The factory returns the app; a separate
indexfile loads configuration, creates the database, starts the job queue and calls the Node adapter’sserve({ fetch: app.fetch, port }). On Workers, the equivalent is exporting the app as the default export (Hono on Cloudflare Workers).
How do you type context and bindings?
Declare context variables once, and every handler reads them with types. In the production API a module augmentation extends Hono’s ContextVariableMap so c.get("auth") is typed as an AuthContext with an actor of admin or publisher and a via of session or bearer, with no casts in handlers (from the repository).
declare module 'hono' {
interface ContextVariableMap {
auth: AuthContext;
viewerEmail: string | null;
}
}
On Workers the same idea applies to platform bindings, which are typed through the Bindings generic and read from c.env: for example, new Hono<{ Bindings: { MY_BUCKET: R2Bucket } }>(). Hono’s documentation also shows generating that type from the Wrangler configuration with wrangler types (Hono on Cloudflare Workers). Typing bindings from the config means a renamed binding becomes a compile error, not a runtime undefined.
How do you write auth middleware that distinguishes callers?
Give each class of caller its own middleware and select by path. The API serves a web admin interface and a command-line publisher with different credentials, so one guard routes by prefix: requests under /api/publisher/ need a bearer token compared in constant time, and everything else needs a signed session cookie that is also checked against a revocation store (from the repository).
Each middleware sets the typed auth variable on success and returns a 401 with the standard error body on failure. Handlers then ask c.get("auth") who is calling and never re-parse headers.
Two details made it safer:
- CSRF is separate and path-aware. Safe methods pass; mutating web requests must send an
X-Requested-Withheader or get a 403; the publisher path is exempt because it uses a bearer token, not a cookie. - Identity headers are attribution, not authorization. The API reads the viewer’s email from the Cloudflare Access header, validates it with a schema, and attaches it for audit logs and preferences, but never uses it to grant access. The code comments say so explicitly, because a header is only as trustworthy as the path that sets it.
How do you get the real client address behind proxies?
Do not trust X-Forwarded-For blindly. The rate limiter’s client address function ignores forwarded headers when the configured number of trusted proxy hops is zero and uses the socket peer. With N greater than zero it takes the Nth entry from the right, which is the one the outermost proxy you control appended, and falls back to the socket if that entry is not a valid IP (from the repository).
This matters on Workers too, where the connecting address arrives in a platform header set by the edge, not in a socket. The rule is the same: choose the single source your own infrastructure sets, and ignore every header a caller can forge.
How do you return one error shape?
Define one error class and one onError handler, and make every failure a JSON body with a code and message. The API’s onError maps its own HttpError (with a status, code and optional details) and Hono’s HTTPException to { error: { code, message } }, logs anything else and returns a generic 500 body that leaks nothing (from the repository). notFound returns the same shape, and the static-file fallback explicitly returns that JSON 404 for unknown /api/ paths instead of serving the single-page app’s HTML.
That last case is easy to miss. A catch-all that serves index.html for unknown routes will answer a mistyped API path with a 200 and HTML, which a client then fails to parse.
How do you validate input?
Use the Zod validator package, or Zod directly inside a thin validator. Hono’s built-in validator is deliberately thin; for JSON and form targets it needs a matching content-type header or the callback receives an empty object, and header keys must be lowercase (Hono validation). The API uses Zod for configuration and for request parsing, for example validating the viewer email header with z.string().email().
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
app.post('/items', zValidator('json', z.object({ title: z.string().min(1) })), (c) => {
const body = c.req.valid('json');
return c.json({ ok: true, title: body.title }, 201);
});
How do you test a Hono API?
Call the app directly. app.request(path, init) returns a Response with no network port, so a test logs in, carries the session cookie, hits a protected route and asserts on status and body. The API’s suite has 51 files in its test directory, and the route tests use app.request for login, the readiness filter on a list route and mutating calls (from the repository).
Because the guards are real middleware in the real app, tests catch ordering mistakes. A test that posts without the CSRF header gets the 403 it should, and a test that hits a publisher path with a session cookie gets a 401.
The health route has its own contract: it reports ok from the database only, so a container health check does not flap on a queue problem, and it separately reports the job queue as up, down or disabled so a dead queue is still visible. That distinction was written down in the handler and covered by a test file of its own.
Where does Hono fit inside another framework?
As an adapter. A queue-monitoring dashboard in a lead-generation platform is mounted at an admin path inside a Next.js App Router catch-all route, with Hono as the bridge to the dashboard’s Hono adapter. The route forwards every HTTP method to the Hono app’s fetch, and a middleware calls the platform’s existing current-user helper and requires the admin role, returning 403 otherwise (from the repository). The route is configured for the Node runtime and dynamic rendering so it is not statically optimized.
This works because Hono’s app is just a fetch function. Anything that can hand it a Request can host it.
What do the Workers in the same estate look like?
They are plain Fetch handlers, and they are the closest thing we run to a Hono Worker. An email-sending Worker exports fetch(request, env), accepts only POST /send, verifies an HMAC-SHA256 signature over the raw body, validates the payload, then maps it to Cloudflare’s email-sending API. Secrets are set with wrangler secret put and typed in an Env interface (from the repository).
Rewriting that Worker in Hono would not change its logic. The route check would become app.post('/send', ...), the signature check a middleware, and env would become c.env typed through Bindings. We would gain routing, typed context and a place to hang shared middleware; we would not gain anything for a single-route Worker. The rule we follow: a Worker with one route stays a plain handler, and a Worker or API with several routes, shared auth and a common error shape earns the framework.
What broke and what we changed
A test hit the wrong path and got a 404. The email Worker enforces its exact route, and a diagnostic test posted to the base URL instead of /send, so it saw 404s that looked like a broken deployment. The Worker was fine; the test was wrong (from the investigation, 2026-11-19). Strict route matching is correct, but the diagnostic should report the path it called.
Forwarded headers are attacker-controlled. Rate limiting keyed on a header the caller can forge is no limit at all, so the client-address function takes an explicit trusted-hop count and defaults to the socket address (from the repository’s comments).
Mutating requests need a defence the cookie does not give. Cookie sessions alone leave state-changing endpoints open to cross-site requests. The CSRF guard requires a custom header on mutating web requests and exempts only the bearer-token path (from the repository).
The SPA fallback hid API errors. Serving index.html for every unknown path made a mistyped API URL return HTML with a 200. The fallback now returns the JSON 404 for any /api/ path.
We have not measured Hono on Workers. This post does not give latency or bundle-size numbers for a deployed Hono Worker, because we have not run one. If you need them, measure your own routes with your own middleware, and compare against a plain Fetch handler baseline.
Related
Frequently asked questions
What is Hono?
Hono is a lightweight web framework that uses the Web Standard Request and Response objects, so the same application code can run on Cloudflare Workers, Deno, Bun, Node.js and other runtimes. It provides routing, middleware, validation helpers and typed context, and it adds adapters where a runtime needs one, as Node does.
How do you deploy Hono on Cloudflare Workers?
Create the Hono app, export it as the default export from the entry file, and point the Wrangler configuration's main field at that file. Type your bindings with the Bindings generic, run the local dev server with Wrangler, and deploy with Wrangler. Secrets are set with a Wrangler command, not committed.
Hono vs Express: which should you use?
Choose Hono if you want the code to run on Workers or other Fetch-based runtimes, or you want typed context and small bundles. Choose Express if you depend on its middleware ecosystem or Node-only libraries. Hono also runs on Node through an adapter, so the move is not all or nothing.
How do you test a Hono API?
Call the app directly, without a network port, using the app's request method with a path and options, and assert on the Response. The test suite we run does this for login, protected routes and error shapes. It keeps tests fast, and it makes middleware order, such as auth before CSRF, visible in a failing test.
Does Hono work with Zod?
Yes. Hono has a built-in thin validator, and a Zod validator package validates JSON, form, query, header and param targets and exposes the typed result through the request's valid method. The built-in validator requires a matching content-type header for JSON and form data or it receives an empty object.
