What are Hono and Elysia, and how is each one positioned?
Hono is a small router and middleware layer built on the Web Standard Request, Response and fetch APIs. Because it depends only on those primitives, the same application runs on Bun, Node.js, Deno and several edge platforms. You change the entry point and adapter, not the handlers. Elysia is designed around Bun first. Its ergonomics and much of its speed come from Bun-specific behavior. It can run elsewhere through adapters, but Bun is the environment it is optimized and tested for.
This article's position is that both frameworks are fast enough that throughput rarely decides between them. Two questions matter more:
- Where must the API run? Bun only, or also on Node.js and edge runtimes.
- How much does your team depend on compile-time type flow from server routes to client calls?
The established alternatives are Express and Fastify on Node.js. Hono and Elysia are both younger, with thinner middleware ecosystems and more API churn between releases. Budget for that when you plan upgrades.
| Dimension | Hono | Elysia |
|---|---|---|
| Design center | Portability across Web Standard runtimes | Bun-first ergonomics and type inference |
| Runtime targets | Bun, Node.js, Deno, multiple edge platforms | Bun primarily; other runtimes via adapters |
| Handler model | Context object; handlers return a Response |
Context object; returned values are serialized automatically |
| Validation approach | Validator middleware with pluggable schema libraries | Built-in TypeBox-based schemas declared on routes |
| Typed client | RPC client inferred from the exported app type | Eden client inferred from the app type |
| Maturity | Young, broader adoption across runtimes | Young, ecosystem centered on Bun |
Who should use Hono or Elysia?
Both frameworks target teams writing HTTP APIs in TypeScript who want a lighter layer than Express or Fastify and who value types that flow from server to client. They suit different teams within that group.
Hono fits teams that:
- Deploy to more than one runtime, or expect to. One example is a service that runs on Bun in containers today and might move some routes to an edge platform later.
- Run platform or shared-library work, where one set of route modules or middleware has to serve services on Bun, Node.js and edge runtimes.
- Want to choose their own validation library, often because Zod or Valibot schemas are already shared with frontends or Node services.
- Ship small, latency-sensitive endpoints to edge isolates, where bundle size and cold-start work matter.
Elysia fits teams that:
- Have committed to Bun for the service's lifetime and want to use Bun-specific features without abstraction layers.
- Work in a TypeScript monorepo where the frontend and backend ship together, so an inferred Eden client removes most hand-written API glue.
- Want one schema declaration to drive validation, handler types and OpenAPI output with minimal setup.
Neither is a good fit for teams that:
- Depend heavily on prebuilt third-party middleware for auth providers, rate limiting, sessions and similar concerns. Express and Fastify have far more of it.
- Need slow-moving, long-stable public APIs and cannot absorb breaking changes between releases.
- Rely on Node-specific libraries that have not been verified on Bun. This is mainly a concern for Elysia, and for Hono only when it runs on Bun.
How does each framework work?
Hono: a fetch handler, a router and a middleware chain
A Hono application is an object that exposes app.fetch(request, env?, ctx?). The runtime, an adapter or a test calls that function with a standard Request. From there:
- Routing. Hono matches the method and path against the registered routes. It ships several router implementations. The default chooses among them, and a regular-expression-based router handles most route tables, while a trie-based router covers patterns the former cannot. You rarely need to choose one yourself.
- Context creation. Hono builds a
Context(c) that wraps the request (c.req), holds per-request variables (c.set/c.get), carries runtime bindings (c.env), and provides response helpers such asc.json()andc.text(). - Middleware composition. Matching middleware and the final handler are composed into one chain in registration order. Each middleware receives
(c, next). Code beforeawait next()runs on the way in and code after it runs on the way out, which is where timing, headers and logging usually go. - Response. The handler returns a standard
Response, usually built through ac.*helper. That object goes straight back to the runtime.
Nothing in this path touches a runtime-specific API, so the core runs unchanged everywhere. Runtime differences are confined to the entry file and to optional helpers for features like static files and WebSockets.
Elysia: a typed builder, lifecycle stages and compiled handlers
An Elysia application is a builder. Each .get(), .post(), .use(), .derive() or hook call registers behavior and returns an instance whose TypeScript type includes everything declared so far. That accumulated type is what Eden reads.
At runtime, a request passes through named lifecycle stages. The broad order is request, parse, transform, before-handle, handler, after-handle and response mapping, with onError taking over if any stage throws. Validation against the route's TypeBox schema runs before the handler, so invalid input is rejected before your code sees it. Handlers return plain values, and Elysia maps them to a Response. Objects become JSON, strings become text, and set.status and set.headers control status and headers.
Much of Elysia's speed comes from preparation done before requests arrive. It inspects which parts of the context each handler and hook actually use, then builds a specialized handler for each route, so per-request work is limited to what that route needs. .listen() starts Bun's built-in server. That step, along with Bun-specific APIs your code may call, is what ties the framework to Bun.
How does each framework run on Bun and on an edge runtime?
"Runs on an edge runtime" means three concrete things. The code uses only Web-standard APIs such as Request, Response, URL, fetch and Web Crypto, with nothing from node:fs or Bun.*. The platform calls a fetch-style handler (Request) => Response instead of your code opening a port. And because isolates start often and may cap script size, cold-start work and bundle size count against you.
Hono is built around that handler. A single app exposes app.fetch, and each target only needs a small entry file:
routes.ts → const app = new Hono()
│
┌───────────────────┼────────────────────┐
bun.ts node.ts worker.ts
export default app serve(app) via export default app
(Bun calls fetch) Node adapter (platform calls fetch)
Moving Hono between targets is mostly a matter of swapping that entry file, because the routes never touch the runtime. The example below shows the Bun case: a route module plus a default export that Bun's server picks up.
Elysia is designed Bun-first, and that design is what makes it harder to move. Code that calls Bun.file, depends on Bun's server for WebSockets, or relies on lifecycle features tied to the Bun server does not port by changing one file. Elysia does publish adapters, but their coverage changes over time, so read its current compatibility documentation before you assume a target is supported.
Hono has its own limits here. It is portable because it targets what every runtime has in common. WebSockets, static file serving and Bun-native APIs still go through runtime-specific helpers, so plan for some per-target code at those edges.
// routes.ts: runtime-agnostic routes using only Web-standard APIs
import { Hono } from 'hono'
export const app = new Hono()
app.get('/health', (c) => c.text('ok'))
app.get('/users/:id', (c) => {
// c.req.param reads the path parameter; no Node or Bun APIs involved
const id = c.req.param('id')
return c.json({ id, name: 'Example User' })
})
app.post('/echo', async (c) => {
// Standard Request body parsing works on every target
const body = await c.req.json()
return c.json({ received: body }, 201)
})
// bun.ts: the only Bun-specific file. Run with: bun run bun.ts
// Bun's server picks up a default export that has a fetch method.
// To target an edge platform instead, write a worker.ts that
// exports the same app; routes.ts stays unchanged.
import { app } from './routes'
export default {
port: 3000,
fetch: app.fetch,
}
A Hono route module that uses only Web-standard APIs, plus a small Bun entry file that hands app.fetch to Bun's server, so changing targets means replacing only the entry file.
How do type safety and typed clients compare between Hono and Elysia?
Both frameworks derive client types from server code, but they get there differently. Elysia infers request and response types as you chain methods on one builder. Each .get(), .post() or .use() returns a new type that carries every route and schema declared so far, and Eden reads typeof app to produce a fully typed client. Hono's types are more opt-in. Route parameters are typed from the path string. Validator middleware, either the built-in validator or a schema adapter, narrows what c.req.valid() returns. The hc client is generated from an exported AppType.
Both models break down in the same places:
- Long chains: a single chain becomes one large type.
- Routes split across files: a module that is not chained loses its route types.
- Generic middleware wrappers: wrappers often erase the context type they pass through.
- Slow tooling: editor and
tscperformance degrades as the route tree grows. - Unreadable errors: type errors can run for screens.
Elysia suffers more because everything lives in one accumulating builder type. To keep inference intact in Hono, chain routes on each sub-app, chain the .route() calls that mount them, and export the type of that chained result. In Elysia, write each module as its own Elysia instance and compose them with .use().
A typed client also couples the frontend's build to the backend's source types. In a monorepo that is convenient: a breaking change fails the frontend's type-check immediately. Across separately versioned repos, you have to publish the server's types as a package and coordinate releases around it.
// --- hono/users.ts: chain on the sub-app so its route types are kept
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'
export const users = new Hono()
.get('/:id', (c) => c.json({ id: c.req.param('id'), name: 'Ada' }))
.post('/', zValidator('json', z.object({ name: z.string() })), (c) => {
const { name } = c.req.valid('json') // narrowed to { name: string }
return c.json({ id: '42', name }, 201)
})
// --- hono/app.ts: chain .route() and export the type of the chained result
const app = new Hono().route('/users', users)
export type AppType = typeof app
// --- frontend (Hono): hc reads AppType at build time
import { hc } from 'hono/client'
const client = hc<AppType>('')
const r = await client.users[':id'].$get({ param: { id: '1' } })
// --- elysia/users.ts: each module is its own chained Elysia instance
import { Elysia, t } from 'elysia'
export const userRoutes = new Elysia({ prefix: '/users' })
.get('/:id', ({ params }) => ({ id: params.id, name: 'Ada' }))
.post('/', ({ body }) => ({ id: '42', name: body.name }), {
body: t.Object({ name: t.String() }), // schema drives body type
})
// --- elysia/app.ts: compose with .use(); the builder type accumulates
const server = new Elysia().use(userRoutes).listen(3000)
export type App = typeof server
// --- frontend (Elysia): Eden infers paths, params and response types
import { treaty } from '@elysiajs/eden'
const api = treaty<App>('localhost:3000')
const { data } = await api.users({ id: '1' }).get()
Route types flow from chained sub-apps into a typed client in both frameworks: Hono uses .route() and an exported AppType with hc, and Elysia uses .use() with Eden's treaty, with each module split into its own file without losing inference.
How should you handle validation and schemas in each framework?
Elysia treats the schema as part of the route definition. You pass a TypeBox object (exposed as t) in the route's body, query or params options, and that single declaration validates the request, narrows the handler's types and feeds the OpenAPI plugin. Nothing has to be kept in sync by hand.
Hono separates these concerns. Its validator middleware takes a function, and adapter middleware connects it to a schema library such as Zod or Valibot. The handler reads the parsed value through c.req.valid('json'), so types still flow from the schema. OpenAPI generation, however, requires a further integration chosen by the team.
| Concern | Elysia | Hono |
|---|---|---|
| Schema format | TypeBox by default | Team's choice via adapters |
| Types from schema | Built in | Built in, via validator middleware |
| OpenAPI | Plugin reads the same schema | Separate integration |
| Main risk | Format lock-in | Library drift across services |
Elysia's approach removes most of the duplicated type and validation code. The cost is that your contracts are written in TypeBox. TypeBox emits JSON Schema, which helps when exporting contracts. But if a Node worker or a frontend form already relies on Zod, you either maintain two definitions or convert between them.
Hono lets you place request schemas in a shared package that non-Bun services import unchanged. That freedom has a cost. Without a written convention, one service ends up on Zod, another on Valibot, and shared contracts stop being shared. Choose one library per organisation, not per repository, and enforce the choice through a lint rule or an internal starter template.
// --- elysia-app.ts: one TypeBox schema drives validation, types and OpenAPI ---
import { Elysia, t } from 'elysia'
const CreateUser = t.Object({
name: t.String({ minLength: 1 }),
age: t.Number({ minimum: 0 }),
})
new Elysia()
.post('/users', ({ body }) => {
// body is typed as { name: string; age: number } from the schema above
return { created: body.name }
}, { body: CreateUser }) // invalid bodies are rejected before the handler runs
.listen(3000)
// --- hono-app.ts: the validator middleware plugs in a library the team chose (Zod here) ---
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'
// This schema has no Bun or Hono dependency, so it can live in a shared
// package that Node services or frontend forms import unchanged.
export const CreateUserSchema = z.object({
name: z.string().min(1),
age: z.number().min(0),
})
const app = new Hono()
app.post('/users', zValidator('json', CreateUserSchema), (c) => {
// c.req.valid('json') returns the parsed body, typed from the Zod schema
const body = c.req.valid('json')
return c.json({ created: body.name }, 201)
})
export default app // Bun serves the default export's fetch handler
The same request body validated in Elysia, where the TypeBox schema is part of the route definition, and in Hono, where a Zod schema that can be shared with other services is attached through validator middleware.
How do middleware, plugins and lifecycle hooks differ?
Both frameworks resolve request handling in registration order, and that one fact causes most of the bugs here.
Hono: a linear middleware chain
Hono middleware is an async (c, next) function registered with app.use(). Per-request state lives on the context: c.set('user', ...) writes it and c.get('user') reads it. Declaring a Variables type on the app or in createMiddleware keeps those reads typed. Shared dependencies such as a database client are usually created once at module scope and attached per request through middleware, or passed through Hono's Env bindings on edge runtimes.
The common ordering mistake is calling app.use('/admin/*', auth) after the admin routes are defined. Those routes match first and never pass through the check. Nothing errors, and the endpoints are simply unprotected.
Elysia: lifecycle hooks and scoped plugins
Elysia splits request handling into named stages such as onRequest, onTransform, onBeforeHandle, onAfterHandle and onError. decorate attaches a static value like a database client once. derive and resolve compute per-request values like the current user. A hook only covers routes registered after it. A hook declared inside a plugin stays local to that plugin unless you widen its scope explicitly, so an auth plugin can appear to work in its own tests but protect nothing in the parent app.
Conventions that prevent this
- Register auth before any routes.
- Keep each guard and the routes it protects in one module.
- Add a test that calls every protected route without credentials and asserts a 401.
Both ecosystems are thinner than older Node frameworks, so plan to write and maintain some middleware yourself.
// --- hono-app.ts ---
import { Hono } from 'hono'
import { createMiddleware } from 'hono/factory'
type Env = { Variables: { userId: string } }
const auth = createMiddleware<Env>(async (c, next) => {
if (c.req.header('Authorization') !== 'Bearer example-token') {
return c.json({ error: 'unauthorized' }, 401)
}
c.set('userId', 'user-123') // per-request state lives on the context
await next()
})
const app = new Hono<Env>()
// PITFALL: this must come before the routes. If it is moved below app.get(),
// /admin/stats matches first, the middleware never runs, and nothing errors.
app.use('/admin/*', auth)
app.get('/admin/stats', (c) => c.json({ user: c.get('userId') }))
// --- elysia-app.ts ---
import { Elysia } from 'elysia'
const authPlugin = new Elysia({ name: 'auth' })
// 'scoped' lifts the hooks to the app that calls .use(). Without it they stay
// local to this plugin and protect nothing in the parent.
.derive({ as: 'scoped' }, ({ headers }) => ({
userId: headers.authorization === 'Bearer example-token' ? 'user-123' : null,
}))
.onBeforeHandle({ as: 'scoped' }, ({ userId, set }) => {
if (!userId) {
set.status = 401
return { error: 'unauthorized' } // returning a value short-circuits the handler
}
})
const api = new Elysia()
.get('/health', () => 'ok') // registered before .use(): intentionally public
.use(authPlugin) // PITFALL: any route above this line is not covered
.get('/admin/stats', ({ userId }) => ({ user: userId }))
The same bearer-token auth check written as Hono middleware and as a scoped Elysia plugin, with comments marking where registration order or plugin scope can silently leave routes unprotected.
Does raw performance matter when choosing between Hono and Elysia?
Published benchmarks for both frameworks usually measure a route that returns a constant string. That isolates router and response overhead, which is the one cost your real endpoints barely notice.
An illustrative estimate
Assume a GET /orders/:id endpoint with these per-request costs. The numbers are assumptions, not measurements:
- Database query over a pooled connection: 3 ms
- Schema validation of params and query: 0.05 ms
- JSON serialization of a 15 KB response: 0.15 ms
- Framework routing and context setup: 0.02 ms
The total is about 3.22 ms, and routing accounts for roughly 0.6% of it. If one framework halved its router overhead, the endpoint would get faster by about 0.01 ms, which is well below the normal variation in your database latency.
Run your own test
Benchmark one realistic endpoint in each framework against the same database, seed data and payload size. Keep these constant:
- Bun version
- Machine and container CPU limits
- Connection pool size
- Logging configuration
A widely used load generator such as wrk works for this, for example wrk -t4 -c64 -d60s --latency pointed at the endpoint. Record p50, p99 and p99.9 latency rather than only throughput. Also sample the server process's CPU time with pidstat or top, then divide by requests served to get CPU per request, which tells you more about cost at scale than peak throughput does.
The bigger decision is often Bun itself. If a driver, telemetry SDK or auth library you depend on relies on Node APIs that Bun implements incompletely, that gap will affect you far more than router speed. Test those libraries early.
What should platform teams check before adopting either framework?
Before committing, run both frameworks through the same operational checklist you would apply to any service in your fleet.
Observability. Confirm where you can attach request IDs, structured logs and trace spans. Hono uses ordinary middleware that wraps await next(), so timing and span creation sit in one function. Elysia spreads this across lifecycle hooks such as onRequest and onAfterHandle. That gives finer control, but you need to check which hook still runs when a handler throws.
Error shape. Decide on one error body format, such as a problem-details style JSON object, and enforce it centrally. Hono provides app.onError and HTTPException. Elysia provides an onError hook that receives an error code, which includes validation failures. If you skip this, clients will see each framework's default error format.
Shutdown. Neither framework handles SIGTERM for you. Keep a reference to the server Bun returns, stop accepting new connections and drain in-flight requests within your orchestrator's grace period.
CI and images. Pin the Bun version in both CI and the container base image. Version drift between them causes failures that only appear after deployment.
Testing. Both frameworks accept a standard Request directly. In Hono you call app.request() or app.fetch(). In Elysia you call app.handle(new Request(...)). No port is opened, so tests run in parallel and you avoid port conflicts in CI.
| Concern | Hono | Elysia |
|---|---|---|
| Error handling | app.onError, HTTPException |
onError hook with error codes |
| Testing | app.request() / app.fetch() |
app.handle(Request) |
| Shutdown | Manual, via Bun server | Manual, via Bun server |
| Observability | Wrapping middleware | Lifecycle hooks |
How can Hono or Elysia save engineering time?
The time savings come from removing work that teams usually repeat by hand. Router speed is not the source.
- No hand-written API clients. Hono's
hcand Elysia's Eden generate typed clients from the server's own type. You stop writing and updating fetch wrappers and request/response interfaces for every endpoint. A renamed field or changed parameter becomes a compile error in the frontend instead of a runtime bug found in QA. - One schema instead of three definitions. Without schema-driven validation, teams often keep a TypeScript interface, a validation function and an OpenAPI description for the same payload. Elysia derives all three from one TypeBox schema. Hono derives the first two from one Zod or Valibot schema and adds OpenAPI through an integration.
- Faster, simpler tests. Because
app.request()andapp.handle()take a standardRequestin-process, route tests need no server startup, port allocation or HTTP client setup. They run in parallel and avoid a common source of flaky CI. - Avoided rewrites (Hono). If a service later needs to move from Bun to Node.js, or some routes need to move to an edge platform, Hono limits the change to an entry file and any runtime-specific helpers. Route handlers stay as they are.
- Less boilerplate on Bun (Elysia). Returning plain values, declaring schemas inline and composing plugins with
.use()keep handlers short when the team has committed to Bun.
An illustrative estimate
The inputs below are assumed for illustration only and are not measured. Assume a service with 40 endpoints. Each endpoint changes shape about once a quarter. Without a typed client, each change takes about 30 minutes to update the client wrapper, the shared interface and the validation code by hand. Over a year, that comes to 40 × 4 × 0.5 = 80 engineer-hours of synchronization work. That figure does not include debugging the mismatches that slip through. With an inferred client and schema-derived types, most of that work becomes fixing the compile errors the change produces.
Your numbers will differ, so substitute your own endpoint count and change rate. Also subtract the costs covered elsewhere in this article: slower type-checking on large route trees, middleware you have to write yourself, and upgrade work caused by API churn. The savings are real when the frontend and backend share types and change often. They are small for a stable API with a single consumer.
When should you choose Hono, when should you choose Elysia, and when should you avoid each?
The choice comes down to how firmly the service is tied to Bun and how much the team gains from schema-first types.
| Requirement | Recommendation | Why |
|---|---|---|
| Deployment targets are mixed or may change | Hono | Built on the Web Fetch API, so the same app runs on Bun, Node.js and edge platforms through thin adapters |
| Edge deployment is a hard requirement | Hono | Edge support is a core design goal, not an afterthought |
| Low runtime lock-in matters | Hono | Handlers depend on standard Request/Response, not on Bun internals |
| Service is committed to Bun long term | Elysia | It is designed around Bun and uses Bun-specific optimizations |
| Schema-driven types and an end-to-end client are the main goal | Elysia | One schema covers validation, inference and the Eden client |
| Moving to Node.js or edge is plausible | Avoid Elysia | The port can be awkward at best and a partial rewrite at worst |
| Heavy reliance on third-party middleware | Fastify or Express | Larger ecosystems with more prebuilt integrations |
| Long-term API stability matters more than ergonomics | Fastify or Express | Longer track record and slower-moving public APIs |
Before you commit, price in these development costs:
- Migration risk. Elysia's coupling to Bun pays off only as long as you stay on Bun.
- Type-check overhead. Deep inference across large route trees can slow the editor and CI in both frameworks. Elysia's chained schemas tend to feel this sooner.
- Schema lock-in. Validation logic written against one framework's schema conventions does not move cleanly to another.
- Cross-repo release coordination. A shared typed client means server type changes must ship alongside client updates. Without that coordination, consumers break at compile time or drift out of sync.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to hono vs elysia, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.