How Hono handles requests: routing, middleware, and context

By

Tagged: JavaScript

Follow one request through Hono to see how routing, middleware, context, Web Standards, and runtime adapters work together.

I like frameworks that disappear when you look closely at them, and Hono is one of those.

You give it a route:

import { Hono } from 'hono'

const app = new Hono()

app.get('/hello/:name', (c) => {
  return c.text(`Hello ${c.req.param('name')}`)
})

export default app

Then a request arrives and a response comes back:

GET /hello/Ada

Hello Ada

What happens between those two moments?

Let’s follow this request through Hono, starting when the application registers the route and stopping when the runtime receives a Web Response. By the end, the small API will make a lot more sense.

Before the request arrives

Our story starts before anyone visits /hello/Ada. The application runs this line:

app.get('/hello/:name', handler)

Hono doesn’t start listening on a port here, and it doesn’t create a response or run the handler. It just records four pieces of information:

method:  GET
path:    /hello/:name
handler: handler
order:   where we registered it

Hono keeps matching handlers in registration order, so middleware and routes registered first get the first chance to handle the request.

For example, this fallback hides the route below it:

app.get('*', (c) => c.text('Not found', 404))
app.get('/hello/:name', handler)

The wildcard returns a response before GET /hello/Ada can reach handler. Put the specific route first instead:

app.get('/hello/:name', handler)
app.get('*', (c) => c.text('Not found', 404))

Now the specific handler gets its chance to respond.

The request enters through fetch()

Now our request arrives:

new Request('http://localhost/hello/Ada')

The center of every Hono application is app.fetch():

const response = await app.fetch(request)

That method receives a standard Web Request and returns a standard Web Response, and that’s what makes Hono portable.

Cloudflare Workers already use Request and Response, and Bun and Deno understand them too. Node.js and AWS Lambda need a small adapter at the edge, but the Hono application in the middle stays the same because it builds on the HTTP model JavaScript runtimes already share.

Hono chooses a router

Once the request enters the application, Hono needs to find a matching route.

A normal new Hono() uses SmartRouter. Instead of matching routes itself forever, it picks another router for your app on the first request. By default, it tries RegExpRouter first, and if the registered patterns don’t fit, it falls back to TrieRouter.

Once Hono finds a router that accepts the full route table, it locks it in so later requests skip the selection step. Conceptually, the first request does this:

load all routes
try RegExpRouter
fall back to TrieRouter if needed
keep the winner
match /hello/Ada

Every request after that starts at the last step.

I like this detail because you pay the setup cost once on the first request, and then every request after it goes straight to the selected router.

The router finds /hello/:name

Our request has a method and a pathname:

GET
/hello/Ada

The router compares them against the registered routes. Static paths like /health are easy because Hono can find them with a direct lookup.

Dynamic paths need more work:

/hello/:name
/posts/:slug
/users/:id/settings

RegExpRouter combines compatible dynamic routes into an optimized matcher instead of walking through a long list and testing each route one by one on every request.

When /hello/Ada matches, the router returns two things:

  • the handler for /hello/:name
  • the position of the name parameter

Hono doesn’t build a full parameter object right away. It waits until your code asks for it:

c.req.param('name')

Only then does Hono turn the captured part of the pathname into Ada. You’ll see that same lazy approach across the rest of Hono, where it avoids parsing data until your handler asks for it.

Hono creates the context

The route matched, but Hono can’t call the handler with the raw Request alone. It creates the Context object you see as c in every handler:

app.get('/hello/:name', (c) => {
  return c.text(`Hello ${c.req.param('name')}`)
})

c holds the request, response helpers, environment bindings, variables, status, and headers for this single trip through the app.

The original Web Request is still right there if you need it:

c.req.raw

Hono wraps it in HonoRequest to add convenient helpers on top:

c.req.param('name')
c.req.query('page')
c.req.header('authorization')
await c.req.json()

That distinction matters whenever a standard Web API already solves your problem, because you can drop straight down to the original Request instead of waiting for a framework-specific wrapper.

Middleware joins the journey

Let’s add one piece of middleware:

app.use('*', async (c, next) => {
  const startedAt = Date.now()

  await next()

  const duration = Date.now() - startedAt
  c.header('Server-Timing', `app;dur=${duration}`)
})

Now /hello/Ada matches two handlers:

  1. the timing middleware
  2. the route handler

Hono composes them in that order. The middleware runs up to await next(), and then Hono enters the route handler, which creates the response:

return c.text('Hello Ada')

Control then returns to the middleware, where it calculates the duration and adds the Server-Timing header. The whole flow looks like this:

timing middleware starts
  route handler runs
  route handler returns a response
timing middleware adds a header
response leaves the application

This is often called onion-style middleware because each layer can run code both before and after the next handler.

A middleware can stop the trip

Now look at an authentication middleware:

app.use('/admin/*', async (c, next) => {
  const token = c.req.header('authorization')

  if (!token) {
    return c.text('Unauthorized', 401)
  }

  await next()
})

If the token is missing, the middleware returns a response without calling next(), so the route handler never runs. That’s how authentication, caching, redirects, and other early responses work in Hono.

c.text() creates a real response

Our handler ends with this line:

return c.text('Hello Ada')

c.text() is convenient, but it isn’t doing anything magical. It builds a standard Web Response with a text body and the right content type, which is just a shorter version of this:

return new Response('Hello Ada', {
  headers: {
    'Content-Type': 'text/plain; charset=UTF-8',
  },
})

Hono includes helpers for the common response types:

c.text('Hello Ada')
c.json({ message: 'Hello Ada' })
c.html('<h1>Hello Ada</h1>')
c.redirect('/login')

They all produce a standard Response. The context also tracks metadata added along the way, so if middleware calls c.header() or a handler calls c.status(), Hono applies those values when it finalizes the response.

By the time app.fetch() resolves, Hono’s job is done. We started with:

GET /hello/Ada

And we end with a response every supported runtime understands:

new Response('Hello Ada')

The adapter has one job

On Cloudflare Workers, the application itself can be the exported fetch handler:

export default app

The runtime already hands you a Web Request and expects a Web Response.

Node.js speaks a different HTTP API, giving you IncomingMessage and ServerResponse objects instead. The Node adapter translates between the two at the boundary:

Node request
  ↓
Web Request
  ↓
Hono application
  ↓
Web Response
  ↓
Node response

The router, middleware, handlers, and context don’t care where the request came from. Because adapters only translate at the runtime edge instead of reimplementing Hono, they stay small.

If you’re new to the runtime side of this, my free Node.js course walks through the HTTP server and request lifecycle from the beginning.

Let’s test the complete journey

Hono exposes app.request() for testing. It creates a request, sends it through the exact same fetch() path, and returns the response:

import { describe, expect, it } from 'vitest'
import app from './app.js'

describe('GET /hello/:name', () => {
  it('greets the person', async () => {
    const response = await app.request('/hello/Ada')

    expect(response.status).toBe(200)
    expect(await response.text()).toBe('Hello Ada')
  })
})

I prefer testing this way over calling a handler directly, because it exercises the route pattern, parameter extraction, middleware, context helpers, and final response together. Those are the pieces that usually disagree in a real app.

You can also pass a full Request when you need custom headers or a body:

const request = new Request('http://localhost/hello/Ada', {
  headers: {
    Authorization: 'Bearer secret',
  },
})

const response = await app.request(request)

That lets you test the HTTP contract directly without starting a local server.

A tiny Hono-like application

Now we can build a tiny version of the path we just traced. You wouldn’t use this router in production. It’s just enough code to make the architecture concrete:

const routes = []

const get = (path, handler) => {
  routes.push({ method: 'GET', path, handler })
}

const fetch = async (request) => {
  const url = new URL(request.url)
  const route = routes.find((route) => {
    return route.method === request.method && route.path === url.pathname
  })

  if (!route) {
    return new Response('Not found', { status: 404 })
  }

  const context = {
    req: request,
    text: (body) => new Response(body),
  }

  return route.handler(context)
}

With that in place, we can register and call a route:

get('/hello', (c) => c.text('Hello Ada'))

const request = new Request('http://localhost/hello')
const response = await fetch(request)

console.log(await response.text()) //Hello Ada

Real Hono adds fast route compilation, parameters, middleware composition, error handling, typed helpers, and runtime adapters, but the core loop is already right here:

register handlers
receive a Request
find the handlers
create a context
return a Response

Because the platform handles the HTTP layer, the framework itself stays small.

How I would use Hono

Hono is a great fit for a focused API on Cloudflare Workers. Think of a webhook receiver that needs to:

  • verify a signature
  • store an event
  • return a quick response

You get clean routing and middleware without hiding Cloudflare bindings or Web APIs, so the code stays close to the runtime.

It also shines when you want the same Request and Response contract in both tests and production. Sharing that contract removes a lot of test boilerplate.

Small services that might switch runtimes down the road benefit from Hono too, since you swap the adapter while keeping your routes and middleware mostly untouched. Even if you never change runtimes, that portability pays off because your code stays tied to a stable Web standard instead of a proprietary request API.

Where I would not use it

Skip Hono if you only need a single static page and don’t need a framework at all.

You should also pause before migrating a large Node.js app that relies heavily on Node-specific middleware. Using Web Request and Response makes the HTTP boundary portable, not your database drivers, file APIs, background jobs, or third-party packages.

For a large full-stack product, figure out how you want to handle rendering, data loading, forms, authentication, and deployment before picking a router. Hono can be part of that stack without owning the whole thing.

What to check when a route does not work

Knowing this request path gives you a straightforward order for debugging.

First, inspect the route table:

console.log(app.routes)

Confirm the method, path, and registration order. Then test the exact request:

const response = await app.request('/hello/Ada')

console.log(response.status)
console.log(await response.text())

If the route works through app.request() but fails after deployment, check the adapter or runtime configuration, since the Hono app itself already handled the request properly.

If the route doesn’t work in the test either, walk through the same steps we followed in this tutorial:

Was the route registered?
Does the method match?
Does the pathname match?
Did earlier middleware return a response?
Did every middleware that continues call await next()?
Did the final handler return a Response?

Tracing it step by step is much faster than treating the framework as a black box.

The whole story

Putting every piece side by side, here’s the full path from app.get() to the Response your runtime sends back:

app.get()
  ↓
route table
  ↓
app.fetch(request)
  ↓
router match
  ↓
context and middleware
  ↓
handler
  ↓
Web Response

That predictability is what makes Hono easy to work with. The router and middleware keep things fast, while every helper still sits directly on top of a standard Request going in and a standard Response coming out.

Want me to talk about your product? You can sponsor this site.

Related posts about js: