,
]
): HonoBase<
IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,
S,
BasePath,
MergedPath
>
//// app.use(path, ...handlers[])
(
path: P,
...handlers: MiddlewareHandler>[]
): HonoBase>
}
```
Sources: [src/types.ts:1431-1449](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts:1431-1449)
```typescript
M5 extends H = H,
M6 extends H = H,
M7 extends H = H,
M8 extends H = H,
M9 extends H = H,
>(
method: M,
path: P,
...handlers: [
H & M1,
H & M2,
H & M3,
H & M4,
H & M5,
H & M6,
H & M7,
H & M8,
H & M9,
H,
]
): HonoBase<
IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,
S &
ToSchema<
M,
MergePath,
I10,
| MergeTypedResponse
| MergeMiddlewareResponse
| MergeMiddlewareResponse
| MergeMiddlewareResponse
| MergeMiddlewareResponse
| MergeMiddlewareResponse
| MergeMiddlewareResponse
| MergeMiddlewareResponse
| MergeMiddlewareResponse
| MergeMiddlewareResponse
>,
BasePath,
MergePath
>
```
Sources: [src/types.ts:1901-1941](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts:1901-1941)
## Route storage and path resolution
### Internal Route Structure and Routing Tables
When handlers are registered through method shortcuts, `app.use()`, or `app.on()`, `HonoBase` invokes its private `#addRoute` method to normalize paths, uppercase method identifiers, and populate internal routing structures. Every registered route is encapsulated as a `RouterRoute` object containing the assigned `basePath`, the fully qualified `path`, the HTTP `method`, and the target `handler`.
```typescript
#addRoute(method: string, path: string, handler: H, baseRoutePath?: string): void {
method = method.toUpperCase()
path = mergePath(this._basePath, path)
const r: RouterRoute = {
basePath:
baseRoutePath !== undefined ? mergePath(this._basePath, baseRoutePath) : this._basePath,
path,
method,
handler,
}
this.router.add(method, path, [handler, r])
this.routes.push(r)
}
```
Sources: [src/hono-base.ts:385-397](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L385-L397)
The `RouterRoute` entries are dual-stored: they are pushed sequentially into the instance's public `routes` array for introspection or sub-application composition, and they are registered directly into the active `router` instance by calling `this.router.add(method, path, [handler, r])`. This associates each route pattern with a tuple containing the handler and its metadata description.
```source
src/hono-base.ts:124| routes: RouterRoute[] = []
```
Sources: [src/hono-base.ts:124](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L124)
> [!NOTE]
> The router implementation stores tuples of `[handler, r]` as values for each registered method and path combination, permitting downstream dispatch logic to access both the executable function and the complete `RouterRoute` descriptor during request matching.
### Path Normalization and Prefix Merging
Path normalization and prefix combining are handled by utility functions imported from `./utils/url`, specifically `mergePath`, `getPath`, and `getPathNoStrict`. Within `#addRoute`, incoming paths are passed through `mergePath(this._basePath, path)` to ensure that any configured application base path prefixes are correctly prepended without redundant slashes or missing separators.
```typescript
method = method.toUpperCase()
path = mergePath(this._basePath, path)
```
Sources: [src/hono-base.ts:386-387](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L386-L387)
The active `getPath` function is selected during instantiation based on the `strict` option flag. If `strict` evaluates to true (the default), `options.getPath ?? getPath` is selected, enforcing exact path matching including trailing slashes. If `strict` is set to false, `getPathNoStrict` is assigned to normalize out trailing slashes during path resolution.
```typescript
const { strict, ...optionsWithoutStrict } = options
Object.assign(this, optionsWithoutStrict)
this.getPath = (strict ?? true) ? (options.getPath ?? getPath) : getPathNoStrict
}
```
Sources: [src/hono-base.ts:170-173](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L170-L173)
> [!CAUTION]
> Modifying the `strict` flag alters how `getPath` processes incoming URLs at runtime; mixing strict and non-strict sub-applications without accounting for trailing slash normalization can lead to unexpected `404 Not Found` responses during lookup matching.
## Sub-application routing and basePath
### Scoped basePath Cloning and Instance Isolation
Modular composition in Hono relies on creating isolated sub-applications and scoping routing prefixes via `.basePath()`. The `.basePath()` method invokes a private `#clone()` helper that instantiates a new Hono instance sharing the parent's underlying `router`, `getPath`, `errorHandler`, `#notFoundHandler`, and `routes` references, while updating the private `_basePath` property through `mergePath(this._basePath, path)`.
```typescript
#clone(): Hono {
const clone = new Hono({
router: this.router,
getPath: this.getPath,
})
clone.errorHandler = this.errorHandler
clone.#notFoundHandler = this.#notFoundHandler
clone.routes = this.routes
return clone
}
```
Sources: [src/hono-base.ts:175-184](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L175-L174)
```typescript
basePath(
path: SubPath
): Hono, MergePath> {
const subApp = this.#clone()
subApp._basePath = mergePath(this._basePath, path)
return subApp
}
```
Sources: [src/hono-base.ts:247-253](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L247-L253)
> [!TIP]
> Calling `.basePath()` does not duplicate the underlying router or existing route collection; instead, it returns a lightweight shadow instance pre-configured with an extended `_basePath` value for subsequent route registrations.
### Composing Sub-Applications with route()
Sub-applications and independent Hono router instances can be merged into a parent application using the `.route()` method. When `.route(path, app)` is invoked, it creates a scoped sub-application at the specified mount path and iterates over all `app.routes` definitions, re-registering each route into the parent's router and route collection.
```typescript
route<
SubPath extends string,
SubEnv extends Env,
SubSchema extends Schema,
SubBasePath extends string,
SubCurrentPath extends string,
>(
path: SubPath,
app: Hono
): Hono> | S, BasePath, CurrentPath> {
const subApp = this.basePath(path)
app.routes.map((r) => {
let handler
if (app.errorHandler === errorHandler) {
handler = r.handler
} else {
handler = async (c: Context, next: Next) =>
(await compose([], app.errorHandler)(c, () => r.handler(c, next))).res
;(handler as any)[COMPOSED_HANDLER] = r.handler
}
subApp.#addRoute(r.method, r.path, handler, r.basePath)
})
return this
}
```
Sources: [src/hono-base.ts:208-232](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L208-L232)
If the mounted sub-application defines a custom error handler differing from the default `errorHandler`, `.route()` wraps each copied route handler in a composed execution block that routes errors through the sub-application's specific error boundary before falling back or continuing execution.
```typescript
if (app.errorHandler === errorHandler) {
handler = r.handler
} else {
handler = async (c: Context, next: Next) =>
(await compose([], app.errorHandler)(c, () => r.handler(c, next))).res
;(handler as any)[COMPOSED_HANDLER] = r.handler
}
```
Sources: [src/hono-base.ts:221-227](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L221-L227)
### External Framework Mounting with mount()
External request handlers and applications built with other frameworks can be integrated into a Hono application using the `.mount()` method. It processes optional `MountOptions` configurations, which accept either a custom `MountOptionHandler` function or an options object containing an `optionHandler` and a `replaceRequest` strategy.
```typescript
mount(
path: string,
applicationHandler: (request: Request, ...args: any) => Response | Promise,
options?: MountOptions
): Hono {
// handle options
let replaceRequest: MountReplaceRequest | undefined
let optionHandler: MountOptionHandler | undefined
if (options) {
if (typeof options === 'function') {
optionHandler = options
} else {
optionHandler = options.optionHandler
if (options.replaceRequest === false) {
replaceRequest = (request) => request
} else {
replaceRequest = options.replaceRequest
}
}
}
```
Sources: [src/hono-base.ts:328-347](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L328-L347)
The request transformation and argument extraction behavior during execution depend on whether explicit options are provided:
| Option Property | Default Behavior | Custom Behavior |
| :--- | :--- | :--- |
| `replaceRequest` | Strips the mounted path prefix from the incoming request URL pathname | Passes the request through a custom `MountReplaceRequest` function or preserves it unchanged if set to `false` |
| `optionHandler` | Passes `[c.env, executionContext]` extracted from the active `Context` | Invokes the custom `MountOptionHandler` function and normalizes its return value into an array |
```typescript
const getOptions: (c: Context) => unknown[] = optionHandler
? (c) => {
const options = optionHandler!(c)
return Array.isArray(options) ? options : [options]
}
: (c) => {
let executionContext: ExecutionContext | undefined = undefined
try {
executionContext = c.executionCtx
} catch {} // Do nothing
return [c.env, executionContext]
}
replaceRequest ||= (() => {
const mergedPath = mergePath(this._basePath, path)
const pathPrefixLength = mergedPath === '/' ? 0 : mergedPath.length
return (request) => {
const url = new URL(request.url)
url.pathname = this.getPath(request).slice(pathPrefixLength) || '/'
return new Request(url, request)
}
})()
```
Sources: [src/hono-base.ts:350-370](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L350-L370)
Once the request transformer and argument extractors are resolved, `.mount()` registers a wildcard route matching `mergePath(path, '*')` with `METHOD_NAME_ALL`, executing the external handler inside a middleware wrapper.
```typescript
const handler: MiddlewareHandler = async (c, next) => {
const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c))
if (res) {
return res
}
await next()
}
this.#addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler)
return this
}
```
Sources: [src/hono-base.ts:372-383](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L372-L383)
## Application-level error handling
### Default Handlers and Customization
Hono provides built-in fallback handlers for unhandled routing misses and runtime exceptions. The default `notFoundHandler` returns a plain text response with status code `404` and the body `404 Not Found`.
```typescript
const notFoundHandler: NotFoundHandler = (c) => {
return c.text('404 Not Found', 404)
}
```
Sources: [src/hono-base.ts:31-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L31-L33)
The default `errorHandler` inspects caught exceptions to check if they implement a `getResponse()` method. If present, it directly returns the response provided by the error instance; otherwise, it formats a generic internal error response.
```typescript
const errorHandler: ErrorHandler = (err, c) => {
if ('getResponse' in err) {
const res = err.getResponse()
return c.newResponse(res.body, res)
}
console.error(err)
return c.text('Internal Server Error', 500)
```
Sources: [src/hono-base.ts:35-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L35-L41)
Applications can override these default behaviors by registering custom handlers via the `.notFound()` and `.onError()` methods, which update the instance's `#notFoundHandler` and `errorHandler` properties and return the modified Hono instance.
```typescript
onError = (handler: ErrorHandler): Hono => {
this.errorHandler = handler
return this
}
/**
* `.notFound()` allows you to customize a Not Found Response.
*
* @see {@link https://hono.dev/docs/api/hono#not-found}
*
* @param {NotFoundHandler} handler - request handler for not-found
* @returns {Hono} changed Hono instance
*
* @example
* ```ts
* app.notFound((c) => {
* return c.text('Custom 404 Message', 404)
* })
* ```
*/
notFound = (handler: NotFoundHandler): Hono => {
this.#notFoundHandler = handler
return this
}
```
Sources: [src/hono-base.ts:271-294](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L271-L294)
### Exception Dispatching and Error Normalization
During request dispatching in `#dispatch()`, runtime exceptions thrown within route handlers or middleware are caught and passed to `#handleError()`. The `#handleError()` method checks if the thrown value is an instance of `Error`; if so, it delegates to the registered `errorHandler`. If the thrown value is not an `Error` instance, it rethrows the raw value.
```typescript
#handleError(err: unknown, c: Context): Response | Promise {
if (err instanceof Error) {
return this.errorHandler(err, c)
}
throw err
}
```
Sources: [src/hono-base.ts:399-404](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L399-L404)
> [!WARNING]
> Non-`Error` exceptions (such as thrown strings or primitives) bypass the custom `errorHandler` entirely and propagate out of `#handleError()`, potentially causing unhandled promise rejections if not caught at the top-level fetch boundary.
When dispatching requests with a single matching handler or via composed middleware chains, exceptions originating from synchronous code execution, asynchronous promise rejections, or unfinalized context states are intercepted and routed through the error handling pipeline.
```typescript
if (matchResult[0].length === 1) {
let res: ReturnType
try {
res = matchResult[0][0][0][0](c, async () => {
c.res = await this.#notFoundHandler(c)
})
} catch (err) {
return this.#handleError(err, c)
}
return res instanceof Promise
? res
.then(
(resolved: Response | undefined) =>
resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
)
.catch((err: Error) => this.#handleError(err, c))
: (res ?? this.#notFoundHandler(c))
}
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler)
return (async () => {
try {
const context = await composed(c)
if (!context.finalized) {
throw new Error(
'Context is not finalized. Did you forget to return a Response object or `await next()`?'
)
}
return context.res
} catch (err) {
return this.#handleError(err, c)
}
})()
}
```
Sources: [src/hono-base.ts:430-466](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L430-L466)
## Fetch interface and runtime execution
### Standard Fetch Handler and Request Dispatching
The `.fetch()` method serves as the primary entry point for Hono applications, adhering to the standard Web Fetch API signature by accepting a `Request` object, optional environment bindings, and an `ExecutionContext`. It delegates directly to the private `#dispatch()` method using `request.method` and the provided bindings.
```typescript
fetch: (
request: Request,
Env?: E['Bindings'] | {},
executionCtx?: ExecutionContext
) => Response | Promise = (request, ...rest) => {
return this.#dispatch(request, rest[1], rest[0], request.method)
}
```
Sources: [src/hono-base.ts:479-485](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L479-L485)
Inside `#dispatch()`, HTTP `HEAD` requests are intercepted and handled specially by delegating to a `GET` dispatch and stripping the response body, returning a new `Response` with a `null` body.
```typescript
if (method === 'HEAD') {
return (async () =>
new Response(null, await this.#dispatch(request, executionCtx, env, 'GET')))()
}
```
Sources: [src/hono-base.ts:413-416](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L413-L416)
For all other methods, path resolution is performed via the configured `getPath` helper, and the router matches the method against the path to produce a `matchResult`. A new `Context` instance is then instantiated with the request, matched route handlers, bindings, and execution context.
```typescript
const path = this.getPath(request, { env })
const matchResult = this.router.match(method, path)
const c = new Context(request, {
path,
matchResult,
env,
executionCtx,
notFoundHandler: this.#notFoundHandler,
})
```
Sources: [src/hono-base.ts:418-427](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L418-L427)
> [!NOTE]
> If a match yields exactly one handler, Hono bypasses the full `[[Middleware Composition|compose]]` pipeline overhead to execute the handler directly, falling back to the not-found handler if unfinalized.
```typescript
// Do not `compose` if it has only one handler
if (matchResult[0].length === 1) {
let res: ReturnType
try {
res = matchResult[0][0][0][0](c, async () => {
c.res = await this.#notFoundHandler(c)
})
} catch (err) {
return this.#handleError(err, c)
}
return res instanceof Promise
? res
.then(
(resolved: Response | undefined) =>
resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
)
.catch((err: Error) => this.#handleError(err, c))
: (res ?? this.#notFoundHandler(c))
}
```
Sources: [src/hono-base.ts:429-448](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L429-L448)
When multiple handlers match, `#dispatch()` invokes `compose` with the matched handlers, error handler, and not-found handler, ensuring that context finalization invariants are strictly enforced on the resulting execution pipeline.
```typescript
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler)
return (async () => {
try {
const context = await composed(c)
if (!context.finalized) {
throw new Error(
'Context is not finalized. Did you forget to return a Response object or `await next()`?'
)
}
return context.res
} catch (err) {
return this.#handleError(err, c)
}
})()
}
```
Sources: [src/hono-base.ts:450-466](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L450-L466)
### Testing Helpers and Service Worker Integration
Hono provides the `.request()` method as a utility primarily designed for testing. It accepts `Request`, string, or `URL` inputs along with optional request initialization options, environment bindings, and execution context, automatically resolving relative paths against a localhost base if necessary.
```typescript
request = (
input: Request | string | URL,
requestInit?: RequestInit,
Env?: E['Bindings'] | {},
executionCtx?: ExecutionContext
): Response | Promise => {
if (input instanceof Request) {
return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx)
}
input = input.toString()
return this.fetch(
new Request(
/^https?:\/\//.test(input) ? input : `http://localhost${mergePath('/', input)}`,
requestInit
),
Env,
executionCtx
)
}
```
Sources: [src/hono-base.ts:499-517](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L499-L517)
For environments adhering to the Service Worker API (such as non-ES module Cloudflare Workers), the `.fire()` method registers a global `fetch` event listener via `addEventListener`, responding to incoming fetch events by invoking `#dispatch()`.
```typescript
fire = (): void => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
addEventListener('fetch', (event: FetchEventLike): void => {
event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method))
})
}
```
Sources: [src/hono-base.ts:536-542](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L536-L542)
> [!WARNING]
> The `.fire()` method is deprecated and should be avoided in modern ES module runtimes; use `fire` from `hono/service-worker` instead.
```typescript
* @deprecated
* Use `fire` from `hono/service-worker` instead.
```
Sources: [src/hono-base.ts:522-523](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L522-L523)
## Related
- [Request Lifecycle](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/request-lifecycle)
- [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context)
- [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts)
---
## Technical docs: Request Lifecycle
URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/request-lifecycle
Relevant source files
The following files were used as context for generating this wiki page:
- [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts)
- [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts)
- [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts)
- [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts)
- [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts)
- [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts)
- [src/helper/streaming/sse.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts)
- [src/adapter/vercel/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/handler.ts)
- [src/router/reg-exp-router/prepared-router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts)
- [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts)
- [src/helper/proxy/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts)
- [src/client/client.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/client/client.ts)
- [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts)
- [src/helper/streaming/stream.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/stream.ts)
- [src/router/linear-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts)
- [src/client/fetch-result-please.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/client/fetch-result-please.ts)
- [src/adapter/service-worker/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/index.ts)
- [src/adapter/cloudflare-workers/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/websocket.ts)
- [src/middleware/serve-static/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/serve-static/index.ts)
- [src/adapter/service-worker/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/handler.ts)
- [src/router/pattern-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts)
- [runtime-tests/workerd/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/workerd/index.ts)
- [src/http-exception.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/http-exception.ts)
- [src/request/constants.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request/constants.ts)
## Overview
The request lifecycle governs how inbound HTTP requests flow through Hono, starting from native runtime objects or serverless gateway event wrappers src/adapter/aws-lambda/handler.ts:318-342, moving through path matching and src/hono-base.ts:418-428, and ending with response finalization or src/http-exception.ts:66-77. It provides the foundational mechanisms for encapsulating requests, lazily decoding bodies, extracting parameters, and managing errors across handlers src/request.ts:51-80, src/request.ts:220-239, src/request.ts:106-128.
Sources: [src/hono-base.ts:418-428](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L418-L428), [src/request.ts:51-80](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L51-L80), [src/request.ts:106-128](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L106-L128), [src/request.ts:220-239](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L220-L239), [src/adapter/aws-lambda/handler.ts:318-342](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L318-L342), [src/http-exception.ts:66-77](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/http-exception.ts#L66-L77)
## Incoming Web Request Encapsulation
### Request Instance Wrapper
The `HonoRequest` class encapsulates standard Fetch `Request` objects, tying them to Hono's routing state, matched parameters, and path resolution. Its constructor accepts the underlying `Request`, an optional path string defaulting to `'/'`, and a match result tuple representing routing outcomes.
```typescript
export class HonoRequest {
raw: Request
#validatedData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData
#matchResult: Result<[unknown, RouterRoute]>
routeIndex: number = 0
path: string
bodyCache: BodyCache = {}
constructor(
request: Request,
path: string = '/',
matchResult: Result<[unknown, RouterRoute]> = [[]]
) {
this.raw = request
this.path = path
this.#matchResult = matchResult
this.#validatedData = {}
}
...
```
Sources: [src/request.ts:36-80](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L36-L80)
> [!NOTE]
> The `routeIndex` property defaults to `0` and determines which matched route segment supplies the active path parameters when multiple sub-applications or nested router matches are evaluated.
> Sources: [src/request.ts:55-55](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L55-L55)
### Symbol Constants and Metadata
Hono exposes dedicated unique symbols to inspect internal request state, such as retrieving match results directly from handler contexts.
| Symbol Constant | Type | Meaning / Purpose |
| :--- | :--- | :--- |
| `GET_MATCH_RESULT` | `unique symbol` | Symbol used to retrieve the internal route match result from request instances. |
```typescript
export const GET_MATCH_RESULT: unique symbol = Symbol()
```
Sources: [src/request/constants.ts:1-1](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request/constants.ts#L1-L1)
## Body Parsing and Stream Buffering
### Lazy Caching and Payload Extraction
The `HonoRequest` class implements a private `#cachedBody` method that manages lazy decoding and cached extraction of request payloads across different formats such as text, JSON, ArrayBuffer, Blob, and FormData. The `BodyCache` type defines the structure holding these cached payloads as partial properties matching the `Body` type definition.
```typescript
type Body = {
json: any
text: string
arrayBuffer: ArrayBuffer
blob: Blob
formData: FormData
}
type BodyCache = Partial
```
Sources: [src/request.ts:20-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L20-L27)
> [!NOTE]
> Request bodies can only be consumed once on standard Fetch `Request` objects. Hono avoids stream consumption errors by caching the result in `bodyCache` and deriving subsequent format requests from already-cached representations when available.
> Sources: [src/request.ts:69-69](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L69-L69), [src/request.ts:220-239](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L220-L239)
### Body Extraction Flow
When a body accessor like `.text()`, `.json()`, or `.parseBody()` is invoked, `#cachedBody` checks if the requested format already exists in `bodyCache`. If another body type was previously extracted and cached, Hono serializes or transforms the existing cached value using an interim `Response` object to satisfy the new format request without reading the underlying stream twice.
```typescript
#cachedBody = (key: keyof Body) => {
const { bodyCache, raw } = this
const cachedBody = bodyCache[key]
if (cachedBody) {
return cachedBody
}
const anyCachedKey = Object.keys(bodyCache)[0]
if (anyCachedKey) {
return (bodyCache[anyCachedKey as keyof Body] as Promise).then((body) => {
if (anyCachedKey === 'json') {
body = JSON.stringify(body)
}
return new Response(body)[key]()
})
}
return (bodyCache[key] = raw[key]())
}
```
Sources: [src/request.ts:220-239](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L220-L239)
> [!WARNING]
> If `json` was previously cached, it must be explicitly serialized via `JSON.stringify()` before being passed into a new `Response` instance to prevent parsing errors during secondary format extractions.
> Sources: [src/request.ts:231-233](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L231-L233)
### Supported Body Methods
Hono exposes direct methods for parsing incoming payloads based on content type expectations, delegating form data parsing to helper utilities and JSON parsing to text extraction followed by `JSON.parse`.
| Method | Return Type | Underlying Mechanism |
| :--- | :--- | :--- |
| `json()` | `Promise` | Retrieves cached text via `#cachedBody('text')` and parses it with `JSON.parse`. |
| `text()` | `Promise` | Invokes `#cachedBody('text')` to consume the raw stream as a string. |
| `parseBody()` | `Promise` | Delegates to the `parseBody` utility function supporting `multipart/form-data` and `application/x-www-form-urlencoded`. |
```typescript
json(): Promise {
return this.#cachedBody('text').then((text: string) => JSON.parse(text))
}
text(): Promise {
return this.#cachedBody('text')
}
async parseBody(options?: Partial) {
return parseBody(this, options)
}
```
Sources: [src/request.ts:212-218](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L212-L218), [src/request.ts:253-271](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L253-L271)
## Parameter and Query Extraction
### Route Parameter Resolution
The `HonoRequest` class provides the `.param()` method to extract dynamic path parameters captured during route matching. Depending on whether a specific key is passed, `.param()` retrieves either a single decoded parameter via `#getDecodedParam()` or an entire dictionary of decoded route parameters via `#getAllDecodedParams()`.
```typescript
param = ParamKeys>(
key: string extends P ? never : P2 extends `${infer _}?` ? never : P2
): string
param> = RemoveQuestion>>(
key: P2
): string | undefined
param(key: string): string | undefined
param(): Simplify>>>
param(key?: string): unknown {
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams()
}
```
Sources: [src/request.ts:94-104](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L94-L104)
> [!NOTE]
> Parameter values are extracted by mapping route table indices from the internal `#matchResult` tuple. If a parameter string contains percent-encoding (`%`), Hono automatically attempts URI component decoding using `tryDecodeURIComponent`.
> Sources: [src/request.ts:106-124](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L106-L124)
### Decoding and Lookup Mechanics
Internal parameter extraction relies on helper routines that inspect the match result array structure and resolve parameter keys against matched path segments.
```typescript
#getDecodedParam(key: string): string | undefined {
const paramKey = this.#matchResult[0][this.routeIndex][1][key]
const param = this.#getParamValue(paramKey)
return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param
}
#getAllDecodedParams(): Record {
const decoded: Record = {}
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1])
for (const key of keys) {
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key])
if (value !== undefined) {
decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value
}
}
return decoded
}
#getParamValue(paramKey: any): string | undefined {
return this.#matchResult[1] ? this.#matchResult[1][paramKey as any] : paramKey
}
```
Sources: [src/request.ts:106-128](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L106-L128)
### Query String Extraction Helpers
Query string parsing is handled by the `.query()` and `.queries()` methods, which delegate directly to URL utility functions `getQueryParam` and `getQueryParams` applied against the request URL.
| Method | Overload Signatures | Underlying Utility | Purpose |
| :--- | :--- | :--- | :--- |
| `query()` | `query(key: string): string \| undefined` `query(): Record` | `getQueryParam(this.url, key)` | Retrieves a single query parameter value or a dictionary of all single-value query parameters. |
| `queries()` | `queries(key: string): string[] \| undefined` `queries(): Record` | `getQueryParams(this.url, key)` | Retrieves all query parameter values as string arrays or a dictionary mapping keys to string arrays. |
```typescript
query(key: string): string | undefined
query(): Record
query(key?: string) {
return getQueryParam(this.url, key)
}
queries(key: string): string[] | undefined
queries(): Record
queries(key?: string) {
return getQueryParams(this.url, key)
}
```
Sources: [src/request.ts:148-171](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L148-L171)
## Serverless Event Adapters
### AWS Lambda and Lambda@Edge Conversion
The AWS Lambda adapter translates API Gateway payloads (`APIGatewayProxyEvent` and `APIGatewayProxyEventV2`) and `Lambda@Edge` records into standard Fetch `Request` objects before dispatching them to the Hono application. The abstract `EventProcessor` class and its concrete implementations (`EventV1Processor` and `EventV2Processor`) extract routing properties, query strings, headers, and cookies to construct the unified request. For `Lambda@Edge`, `createRequest()` parses CloudFront event structures, resolves host headers from distribution domain names, and decodes base64-encoded request bodies via `decodeBase64`.
```typescript
export class EventV2Processor extends EventProcessor {
protected getPath(event: APIGatewayProxyEventV2): string {
return event.rawPath
}
protected getMethod(event: APIGatewayProxyEventV2): string {
return event.requestContext.http.method
}
protected getQueryString(event: APIGatewayProxyEventV2): string {
return event.rawQueryString
}
...
```
Sources: [src/adapter/aws-lambda/handler.ts:404-415](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L404-L415), [src/adapter/lambda-edge/handler.ts:152-184](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts#L152-L184)
> [!CAUTION]
> When processing V1 API Gateway integration events, query parameters originating from `multiValueQueryStringParameters` or `queryStringParameters` are re-encoded explicitly using `encodeURIComponent` to preserve the original URL format and prevent downstream parsing discrepancies.
> Sources: [src/adapter/aws-lambda/handler.ts:453-468](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L453-L468)
### Cloudflare Pages and Service Workers
Cloudflare Pages integration uses an `handle` function that accepts an `EventContext` containing the incoming `request`, `env` bindings, and execution controls like `waitUntil` and `passThroughOnException`. The handler passes these directly into `app.fetch()`. Similarly, the Service Worker adapter wraps fetch events via `evt.respondWith()`, passing `evt` as the [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) and executing a fallback fetch to `opts.fetch` when a response yields a `404 Not Found` status.
```typescript
export const handle =
(
app: Hono
): PagesFunction =>
(eventContext) => {
return app.fetch(
eventContext.request,
{ ...eventContext.env, eventContext },
{
waitUntil: eventContext.waitUntil,
passThroughOnException: eventContext.passThroughOnException,
props: {},
}
)
}
```
Sources: [src/adapter/cloudflare-pages/handler.ts:32-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L32-L46), [src/adapter/service-worker/handler.ts:18-36](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/handler.ts#L18-L36)
### Lightweight Platform Handlers
Platform adapters for Netlify and Vercel act as thin transparent wrappers, directly binding standard `Request` objects and runtime execution contexts into the Hono application's core `app.fetch()` pipeline without additional payload transformation layers.
| Adapter Module | Target Platform | Argument Signature | Core Dispatch Mechanism |
| :--- | :--- | :--- | :--- |
| `src/adapter/netlify/handler.ts` | Netlify Functions | `(req: Request, context: any)` | `app.fetch(req, { context })` |
| `src/adapter/vercel/handler.ts` | Vercel Serverless | `(req: Request)` | `app.fetch(req)` |
```typescript
export const handle = (
app: Hono
): ((req: Request, context: any) => Response | Promise) => {
return (req: Request, context: any) => {
return app.fetch(req, { context })
}
}
```
Sources: [src/adapter/netlify/handler.ts:4-9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts#L4-L9), [src/adapter/vercel/handler.ts:4-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/handler.ts#L4-L7)
## HTTP Exception Processing
### HTTPException Class Semantics
The `HTTPException` class extends the native `Error` constructor to handle application-level faults such as authentication failures or invalid input. It accepts a `ContentfulStatusCode` status code which defaults to `500`, along with an optional `HTTPExceptionOptions` object containing custom properties.
```typescript
export class HTTPException extends Error {
readonly res?: Response
readonly status: ContentfulStatusCode
constructor(status: ContentfulStatusCode = 500, options?: HTTPExceptionOptions) {
super(options?.message, { cause: options?.cause })
this.res = options?.res
this.status = status
}
...
```
Sources: [src/http-exception.ts:46-59](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/http-exception.ts#L46-L59)
> [!NOTE]
> `HTTPException` supports an optional `cause` property passed directly to the underlying `Error` constructor, allowing error cause chaining during exception propagation.
> Sources: [src/http-exception.ts:14-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/http-exception.ts#L14-L18), [src/http-exception.ts:55-56](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/http-exception.ts#L55-L56)
### Response Generation and Propagation
The `getResponse()` method translates the exception into a standard Fetch `Response` object. If an explicit `res` response object was supplied in the constructor options, a new `Response` is instantiated using its body and headers combined with the exception's `status`. Otherwise, it falls back to creating a plain text response containing the error message and the status code.
```typescript
getResponse(): Response {
if (this.res) {
const newResponse = new Response(this.res.body, {
status: this.status,
headers: this.res.headers,
})
return newResponse
}
return new Response(this.message, {
status: this.status,
})
}
}
```
Sources: [src/http-exception.ts:66-77](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/http-exception.ts#L66-L77)
## Upstream Request Forwarding
### Proxy Initialization and Request Building
The `proxy` helper wraps standard Fetch API dispatches to forward incoming client requests to upstream origin servers. It accepts an input target and optional `ProxyRequestInit` configuration options, supporting custom fetch handlers and strict RFC compliance processing.
Sources: [src/helper/proxy/index.ts:46-48](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L46-L48), [src/helper/proxy/index.ts:160-166](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L160-L166)
The `buildRequestInitFromRequest` helper clones incoming request properties, initializing the `duplex` property to `'half'` when a request body is present. It filters out hop-by-hop headers defined in the specification and evaluates strict RFC compliance when requested.
Sources: [src/helper/proxy/index.ts:50-91](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L50-L91)
| Hop-by-Hop Header | Action |
| :--- | :--- |
| `connection` | Deleted or parsed per `strictConnectionProcessing` |
| `keep-alive` | Deleted |
| `proxy-authenticate` | Deleted |
| `proxy-authorization` | Deleted |
| `te` | Deleted |
| `trailer` | Deleted |
| `transfer-encoding` | Deleted |
| `upgrade` | Deleted |
Sources: [src/helper/proxy/index.ts:10-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L10-L19), [src/helper/proxy/index.ts:80-82](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L80-L82)
> [!WARNING]
> By default, `strictConnectionProcessing` is set to `false`, causing the `Connection` header to be ignored to prevent potential Hop-by-Hop Header Injection attacks from untrusted clients.
> Sources: [src/helper/proxy/index.ts:35-36](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L35-L36), [src/helper/proxy/index.ts:164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L164)
### Header Preprocessing and Validation
When `strictConnectionProcessing` is enabled, the helper splits the `connection` header value by commas and validates each entry against `ALLOWED_TOKEN_PATTERN` to ensure proper token syntax. If an invalid header name is encountered, an `HTTPException` with status `400` is thrown.
Sources: [src/helper/proxy/index.ts:21-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L21-L22), [src/helper/proxy/index.ts:60-77](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L60-L77)
```typescript
const ALLOWED_TOKEN_PATTERN = /^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/
```
Sources: [src/helper/proxy/index.ts:21-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L21-L22)
> [!CAUTION]
> Enabling `strictConnectionProcessing` parses and removes listed headers per RFC 9110 Section 7.6.1 and should only be used in trusted internal environments.
> Sources: [src/helper/proxy/index.ts:37-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L37-L41), [src/helper/proxy/index.ts:60-77](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L60-L77)
The `preprocessRequestInit` function normalizes custom header initializers supplied as plain objects into standard `Headers` instances, deleting entries where the value evaluates to `null` or `undefined`.
Sources: [src/helper/proxy/index.ts:93-113](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L93-L113)
### Dispatch and Response Sanitization
After constructing the upstream request, the helper deletes the `accept-encoding` header and dispatches the request using either `customFetch` or the global `fetch` function.
Sources: [src/helper/proxy/index.ts:168-174](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L168-L174)
```typescript
const req = new Request(input, {
...buildRequestInitFromRequest(raw, strictConnectionProcessing),
...preprocessRequestInit(requestInit as RequestInit),
})
req.headers.delete('accept-encoding')
const res = await (customFetch || fetch)(req)
```
Sources: [src/helper/proxy/index.ts:168-174](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L168-L174)
Response headers are sanitized by removing all hop-by-hop headers. If a `content-encoding` header is present on the upstream response, both `content-encoding` and `content-length` are deleted because the content length no longer matches the uncompressed payload size.
Sources: [src/helper/proxy/index.ts:175-189](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L175-L189)
## Related
- [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core)
- [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context)
- [Middleware Composition](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/middleware-composition)
---
## Technical docs: Execution Context
URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context
Relevant source files
The following files were used as context for generating this wiki page:
- [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts)
- [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts)
- [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts)
- [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts)
- [src/helper/streaming/sse.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts)
- [src/helper/route/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts)
- [src/middleware/jsx-renderer/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts)
- [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts)
- [src/middleware/request-id/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/index.ts)
- [src/helper/streaming/stream.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/stream.ts)
- [src/helper/streaming/text.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/text.ts)
- [src/middleware/timing/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/index.ts)
- [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts)
- [src/adapter/aws-lambda/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/types.ts)
- [src/middleware/context-storage/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts)
- [src/jsx/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/context.ts)
- [src/helper/adapter/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts)
- [src/adapter/bun/server.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/server.ts)
- [src/adapter/lambda-edge/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/conninfo.ts)
- [src/middleware/language/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/index.ts)
- [src/middleware/secure-headers/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/index.ts)
- [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts)
- [src/helper/testing/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/testing/index.ts)
- [src/middleware/jwt/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/index.ts)
- [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts)
## Overview
The `Context` class manages the complete execution lifecycle for incoming HTTP requests [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L293-L361). It encapsulates routing parameters, request headers, environment bindings, and response generation utilities within a unified interface passed to handlers and middleware [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L315-L434), [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L94-L198).
Sources: [src/context.ts:293-361](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L293-L361)
Sources: [src/context.ts:315-434](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L315-L434), [src/request.ts:94-198](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L94-L198)
## Context Lifecycle and Internal State
### Constructor Initialization and Request Wrapping
The `Context` class constructor takes a raw Web Standard `Request` object and an optional `ContextOptions` record [src/context.ts:352-361](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L352-L361). It retains the underlying request as `#rawRequest` and initializes instance parameters such as execution contexts, environment bindings, not-found handlers, path specifications, and routing match results if provided [src/context.ts:300-360](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L300-L360).
Sources: [src/context.ts:352-361](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L352-L361)
Request parsing is deferred via the `.req` getter property, which lazily instantiates a `HonoRequest` wrapper around `#rawRequest`, `#path`, and `#matchResult` upon first access [src/context.ts:366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L366-L369). Similarly, Cloudflare Pages middleware integration constructs a `Context` instance by passing the event execution context alongside extended bindings [src/adapter/cloudflare-pages/handler.ts:60-64](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L60-L64).
Sources: [src/context.ts:366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L366-L369)
Sources: [src/adapter/cloudflare-pages/handler.ts:60-64](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L60-L64)
```typescript
constructor(req: Request, options?: ContextOptions) {
this.#rawRequest = req
if (options) {
this.#executionCtx = options.executionCtx
this.env = options.env
this.#notFoundHandler = options.notFoundHandler
this.#path = options.path
this.#matchResult = options.matchResult
}
}
```
Sources: [src/context.ts:352-361](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L352-L361)
```typescript
return async (executionCtx) => {
const context = new Context(executionCtx.request, {
env: { ...executionCtx.env, eventContext: executionCtx },
executionCtx,
})
```
Sources: [src/adapter/cloudflare-pages/handler.ts:60-64](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L60-L64)
### Execution State and Response Tracking
An active `Context` instance maintains internal tracking flags and response fields throughout the handler execution cycle [src/context.ts:315-345](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L315-L345). The `finalized` boolean flag marks whether a response has been committed or set [src/context.ts:317](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L317). Platform-specific capabilities such as Cloudflare Workers event bindings are accessed through strict getters: the `event` getter verifies the presence of `respondWith` on the execution context, while the `executionCtx` getter validates standard platform contexts, throwing errors if accessed outside a supported environment [src/context.ts:377-397](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L377-L397).
Sources: [src/context.ts:315-345](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L315-L345)
Sources: [src/context.ts:317](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L317)
Sources: [src/context.ts:377-397](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L377-L397)
```typescript
get res(): Response {
return (this.#res ||= createResponseInstance(null, {
headers: (this.#preparedHeaders ??= new Headers()),
}))
}
/**
* Sets the Response object for the current request.
*
* @param _res - The Response object to set.
*/
set res(_res: Response | undefined) {
if (this.#res && _res) {
_res = createResponseInstance(_res.body, _res)
for (const [k, v] of this.#res.headers.entries()) {
if (k === 'content-type') {
continue
}
if (k === 'set-cookie') {
const cookies = this.#res.headers.getSetCookie()
_res.headers.delete('set-cookie')
for (const cookie of cookies) {
_res.headers.append('set-cookie', cookie)
}
} else {
_res.headers.set(k, v)
}
}
}
this.#res = _res
this.finalized = true
}
```
Sources: [src/context.ts:403-434](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L403-L434)
> [!NOTE]
> Setting the response property (`c.res = ...`) automatically marks the context as finalized and copies existing header entries—such as preserving set-cookie arrays and skipping duplicate content types—into the incoming response instance [src/context.ts:414-434](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L414-L434).
Sources: [src/context.ts:414-434](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L414-L434)
The table below details the internal state properties managed directly within the `Context` class instance.
| Field / Property | Internal Variable | Type | Description |
| :--- | :--- | :--- | :--- |
| `req` | `#req`, `#rawRequest` | `HonoRequest \| undefined`, `Request` | Lazily wrapped request accessor and underlying fetch request [src/context.ts:300-301, 366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L300-L301) |
| `env` | `env` | `E['Bindings']` | Environment variables, secrets, and bindings object [src/context.ts:315](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L315) |
| `error` | `error` | `Error \| undefined` | Captured error object thrown during middleware or handler execution [src/context.ts:333](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L333) |
| `event` | `#executionCtx` | `FetchEventLike` | FetchEvent instance supporting `respondWith` [src/context.ts:336, 377-383](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L336) |
| `executionCtx` | `#executionCtx` | `ExecutionContext` | Platform execution context supporting methods like `waitUntil` [src/context.ts:336, 391-397](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L336) |
| `res` | `#res`, `#preparedHeaders` | `Response`, `Headers \| undefined` | Current response object and prepared headers buffer [src/context.ts:337, 341, 403-407](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L337) |
| `finalized` | `finalized` | `boolean` | Flag indicating whether the response has been sent or locked [src/context.ts:317](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L317) |
Sources: [src/context.ts:300-434](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L300-L434)
## Request Parameter and Header Accessors
### HonoRequest Initialization and Parameter Retrieval
The `Context` instance exposes incoming request properties through its `.req` property [src/context.ts:366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L366-L369). Accessing `c.req` triggers the lazy instantiation of a `HonoRequest` wrapper, combining the raw underlying `Request` object with route path variables and match results [src/context.ts:366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L366-L369).
Sources: [src/context.ts:366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L366-L369)
```typescript
get req(): HonoRequest {
this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult)
return this.#req
}
```
Sources: [src/context.ts:366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L366-L369)
> [!NOTE]
> The `HonoRequest` instance is initialized precisely on first access (`this.#req ??= ...`), avoiding parsing overhead for requests that do not inspect parameters, headers, or query strings [src/context.ts:366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L366-L369).
Sources: [src/context.ts:366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L366-L369)
## Variable Storage and Context Typing
### Context Variable Map and Generic Constraints
The `Context` class manages scoped variables across middleware and request handlers via a private `#var` instance of JavaScript's `Map` [src/context.ts:316](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L316). These variables are typed through the generic `E` constraint parameter extending `Env`, allowing applications to define strict typing for key-value pairs shared during request execution [src/context.ts:293-295](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L293-L295).
Sources: [src/context.ts:316](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L316)
Sources: [src/context.ts:293-295](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L293-L295)
```typescript
#var: Map | undefined
```
Sources: [src/context.ts:316](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L316)
> [!NOTE]
> The internal `#var` map is lazily initialized on first write or read operation, preventing unnecessary allocation for request contexts that do not utilize scoped variables [src/context.ts:316](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L316).
Sources: [src/context.ts:316](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L316)
## Response Construction and Helpers
### Response Instance Creation and Default Types
Response generation relies on underlying Web Standard constructor wrappers [src/context.ts:288-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L288-L291). The helper `createResponseInstance` wraps `new Response(body, init)`, providing the foundation for text, stream, and binary outputs [src/context.ts:288-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L288-L291). Additionally, `TEXT_PLAIN` defines the default UTF-8 plain text content type string [src/context.ts:279](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L279), while `setDefaultContentType` merges content type headers with existing header records [src/context.ts:281-286](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L281-L286).
Sources: [src/context.ts:288-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L288-L291)
Sources: [src/context.ts:279](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L279), [src/context.ts:281-286](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L281-L286)
```typescript
export const TEXT_PLAIN = 'text/plain; charset=UTF-8'
const setDefaultContentType = (contentType: string, headers?: HeaderRecord): HeaderRecord => {
return {
'Content-Type': contentType,
...headers,
}
}
const createResponseInstance = (
body?: BodyInit | null | undefined,
init?: globalThis.ResponseInit
): Response => new Response(body, init)
```
Sources: [src/context.ts:279-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L279-L291)
> [!WARNING]
> Modifying headers after a response has been finalized forces Hono to instantiate a new underlying `Response` object to prevent mutation errors on immutable response streams [src/context.ts:516-518](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L516-L518).
Sources: [src/context.ts:516-518](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L516-L518)
### Stream SSE Execution Walkthrough
The `streamSSE` helper orchestrates Server-Sent Events by initializing a transform stream, invoking `c.header` to configure transport headers, and utilizing `createResponseInstance` to generate the final response [src/helper/streaming/sse.ts:72-100](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L72-L100), [src/context.ts:288-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L288-L291).
Sources: [src/helper/streaming/sse.ts:72-100](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L72-L100), [src/context.ts:288-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L288-L291)
1. `streamSSE` initializes a `TransformStream` and wraps it in an `SSEStreamingApi` instance [src/helper/streaming/sse.ts:77-78](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L77-L78).
2. `isOldBunVersion()` checks for legacy runtime behavior, binding an abort listener to `c.req.raw.signal` if necessary [src/helper/streaming/sse.ts:80-87](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L80-L87).
3. `contextStash.set` caches the context against the response readable stream to prevent premature garbage collection in Bun [src/helper/streaming/sse.ts:89-90](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L89-L90).
4. `c.header` sets required transport and protocol headers including `Transfer-Encoding`, `Content-Type`, `Cache-Control`, and `Connection` [src/helper/streaming/sse.ts:92-95](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L92-L95), [src/context.ts:515-527](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L515-L527).
5. `run` executes the user callback with error handling and automatic stream closure [src/helper/streaming/sse.ts:47-68](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L47-L68), [97](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L97).
6. `createResponseInstance` is invoked through response helpers to construct the final Response wrapping `stream.responseReadable` [src/helper/streaming/sse.ts:99](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L99), [src/context.ts:288-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L288-L291).
Sources: [src/helper/streaming/sse.ts:77-78](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L77-L78)
Sources: [src/helper/streaming/sse.ts:80-87](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L80-L87)
Sources: [src/helper/streaming/sse.ts:89-90](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L89-L90)
Sources: [src/helper/streaming/sse.ts:92-95](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L92-L95), [src/context.ts:515-527](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L515-L527)
Sources: [src/helper/streaming/sse.ts:47-68](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L47-L68), [src/helper/streaming/sse.ts:97](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L97)
Sources: [src/helper/streaming/sse.ts:99](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L99), [src/context.ts:288-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L288-L291)
```typescript
export const streamSSE = (
c: Context,
cb: (stream: SSEStreamingApi) => Promise,
onError?: (e: Error, stream: SSEStreamingApi) => Promise
): Response => {
const { readable, writable } = new TransformStream()
const stream = new SSEStreamingApi(writable, readable)
// Until Bun v1.1.27, Bun didn't call cancel() on the ReadableStream for Response objects from Bun.serve()
if (isOldBunVersion()) {
c.req.raw.signal.addEventListener('abort', () => {
if (!stream.closed) {
stream.abort()
}
})
}
// in bun, `c` is destroyed when the request is returned, so hold it until the end of streaming
contextStash.set(stream.responseReadable, c)
c.header('Transfer-Encoding', 'chunked')
c.header('Content-Type', 'text/event-stream')
c.header('Cache-Control', 'no-cache')
c.header('Connection', 'keep-alive')
run(stream, cb, onError)
return c.newResponse(stream.responseReadable)
}
```
Sources: [src/helper/streaming/sse.ts:72-100](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L72-L100)
```mermaid
sequenceDiagram
participant streamSSE as streamSSE (sse.ts)
participant Context as Context (context.ts)
participant header as header (context.ts)
participant createResponseInstance as createResponseInstance (context.ts)
streamSSE->>Context: c.header('Transfer-Encoding', 'chunked')
Context->>header: header(name, value, options)
streamSSE->>Context: c.newResponse(stream.responseReadable)
Context->>createResponseInstance: createResponseInstance(body, init)
```
Sources: [src/helper/streaming/sse.ts:72-100](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L72-L100), [src/context.ts:288-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L288-L291)
> [!NOTE]
An internal `contextStash` WeakMap holds a reference to the active `Context` keyed by `stream.responseReadable`, ensuring the request context remains accessible throughout long-lived streaming connections [src/helper/streaming/sse.ts:70-90](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L70-L90).
Sources: [src/helper/streaming/sse.ts:70-90](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L70-L90)
## Adapter Bindings and Environment Access
### Runtime Identification and Environment Resolution
Hono resolves environment bindings and execution contexts across heterogeneous JavaScript runtimes by combining runtime detection helpers with platform-specific adapter handlers. The `getRuntimeKey()` utility inspects `globalThis` properties and user agent strings to classify the active platform into one of the supported runtime identifiers [src/helper/adapter/index.ts:50-84](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L50-L84). Once identified, the `env()` helper dynamically dispatches to the correct environment provider, returning process environment variables or platform-native binding stores [src/helper/adapter/index.ts:10-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L10-L41).
Sources: [src/helper/adapter/index.ts:50-84](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L50-L84)
Sources: [src/helper/adapter/index.ts:10-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L10-L41)
| Runtime Key | Detection Mechanism | Environment Source |
| :--- | :--- | :--- |
| `bun` | `navigator.userAgent` starts with `Bun` | `process.env` |
| `node` | `navigator.userAgent` starts with `Node.js` or `process.release.name === 'node'` | `process.env` |
| `deno` | `navigator.userAgent` starts with `Deno` | `Deno.env.toObject()` |
| `workerd` | `navigator.userAgent` starts with `Cloudflare-Workers` | `c.env` |
| `edge-light` | `globalThis.EdgeRuntime` is a string | `process.env` |
| `fastly` | `globalThis.fastly !== undefined` | `{}` |
| `other` | Fallback when no platform signature matches | `{}` |
Sources: [src/helper/adapter/index.ts:8-48](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L8-L48)
```typescript
export type Runtime = 'node' | 'deno' | 'bun' | 'workerd' | 'fastly' | 'edge-light' | 'other'
export const env = <
T extends Record,
C extends Context = Context<{
Bindings: T
}>,
>(
c: T extends Record ? Context : C,
runtime?: Runtime
): T & C['env'] => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const global = globalThis as any
const globalEnv = global?.process?.env as T
runtime ??= getRuntimeKey()
const runtimeEnvHandlers: Record T> = {
bun: () => globalEnv,
node: () => globalEnv,
'edge-light': () => globalEnv,
deno: () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return Deno.env.toObject() as T
},
workerd: () => c.env,
// On Fastly Compute, you can use the ConfigStore to manage user-defined data.
fastly: () => ({}) as T,
other: () => ({}) as T,
}
return runtimeEnvHandlers[runtime]()
}
export const knownUserAgents: Partial> = {
deno: 'Deno',
bun: 'Bun',
workerd: 'Cloudflare-Workers',
node: 'Node.js',
}
```
Sources: [src/helper/adapter/index.ts:8-48](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L8-L48)
> [!NOTE]
> The `env()` helper requires an explicit runtime parameter or falls back to `getRuntimeKey()`, which inspects `navigator.userAgent` before checking runtime-specific global objects [src/helper/adapter/index.ts:17-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L17-L23).
Sources: [src/helper/adapter/index.ts:17-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L17-L23)
### Platform Adapter Handlers and Execution Contexts
Cloudflare Pages, AWS Lambda, and Netlify integrate with Hono by mapping native platform events and execution contexts into the standard `app.fetch()` signature [src/adapter/aws-lambda/handler.ts:268-272](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L268-L272), [src/adapter/cloudflare-pages/handler.ts:37-45](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L37-L45), [src/adapter/netlify/handler.ts:8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts#L8). Cloudflare Pages passes `eventContext.request`, environment bindings augmented with `eventContext`, and an execution options object containing `waitUntil` and `passThroughOnException` callbacks [src/adapter/cloudflare-pages/handler.ts:37-45](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L37-L45).
Sources: [src/adapter/aws-lambda/handler.ts:268-272](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L268-L272), [src/adapter/cloudflare-pages/handler.ts:37-45](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L37-L45), [src/adapter/netlify/handler.ts:8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts#L8)
Sources: [src/adapter/cloudflare-pages/handler.ts:37-45](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L37-L45)
```typescript
export const handle =
(
app: Hono
): PagesFunction =>
(eventContext) => {
return app.fetch(
eventContext.request,
{ ...eventContext.env, eventContext },
{
waitUntil: eventContext.waitUntil,
passThroughOnException: eventContext.passThroughOnException,
props: {},
}
)
}
```
Sources: [src/adapter/cloudflare-pages/handler.ts:32-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L32-L46)
AWS Lambda adapters process incoming API Gateway or ALB events via event processors (`EventV1Processor` and `EventV2Processor`), converting event payloads into standard `Request` instances and passing the raw `event`, `requestContext`, and `lambdaContext` through to `app.fetch()` [src/adapter/aws-lambda/handler.ts:252-272](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L252-L272). Similarly, Netlify's adapter delegates incoming requests directly to `app.fetch()` accompanied by the Netlify execution context object [src/adapter/netlify/handler.ts:4-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts#L4-L10). Connection info helpers, such as the Lambda@Edge implementation, extract client IP addresses directly from nested event records stored within `c.env` [src/adapter/lambda-edge/conninfo.ts:11-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/conninfo.ts#L11-L14).
Sources: [src/adapter/aws-lambda/handler.ts:252-272](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L252-L272)
Sources: [src/adapter/netlify/handler.ts:4-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts#L4-L10)
Sources: [src/adapter/lambda-edge/conninfo.ts:11-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/conninfo.ts#L11-L14)
```typescript
return async (event, lambdaContext?) => {
const processor = getProcessor(event)
let req, requestContext
try {
req = processor.createRequest(event)
requestContext = getRequestContext(event)
} catch (error) {
console.error('Error processing request:', error)
const errorResponse =
error instanceof TypeError
? new Response('Invalid request', { status: 400 })
: new Response('Internal Server Error', { status: 500 })
return processor.createResult(event, errorResponse, { isContentTypeBinary })
}
const res = await app.fetch(req, {
event,
requestContext,
lambdaContext,
})
return processor.createResult(event, res, { isContentTypeBinary })
}
}
```
Sources: [src/adapter/aws-lambda/handler.ts:252-276](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L252-L276)
> [!WARNING]
> Accessing `c.event` or `c.executionCtx` on platforms that do not supply a matching execution context object will throw an explicit error (`This context has no FetchEvent` or `This context has no ExecutionContext`) [src/context.ts:377-397](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L377-L397).
Sources: [src/context.ts:377-397](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L377-L397)
## Related
- [Request Lifecycle](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/request-lifecycle)
- [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core)
- [Context Storage](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/context-storage)
---
## Technical docs: Middleware Composition
URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/middleware-composition
Relevant source files
The following files were used as context for generating this wiki page:
- [src/compose.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts)
- [src/middleware/combine/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts)
- [src/helper/factory/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts)
- [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts)
- [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts)
- [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts)
- [src/validator/validator.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/validator/validator.ts)
- [src/utils/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/handler.ts)
- [src/middleware/cache/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts)
- [src/helper/streaming/stream.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/stream.ts)
- [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts)
- [src/middleware/language/language.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts)
- [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts)
- [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts)
## Overview
Middleware composition in Hono orchestrates request processing pipelines through recursive dispatching and onion-model execution [src/compose.ts:15-72](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L15-L72). By combining middleware functions, conditional routing helpers, and type-safe factories, Hono enables modular request interception, error handling, and terminal route delegation [src/compose.ts:15-72](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L15-L72), [src/middleware/combine/index.ts:38-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L164), [src/helper/factory/index.ts:353-360](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L353-L360).
Sources: [src/compose.ts:15-72](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L15-L72), [src/middleware/combine/index.ts:38-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L164), [src/helper/factory/index.ts:353-360](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L353-L360), [src/types.ts:305-347](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts#L305-L347), [src/utils/handler.ts:8-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/handler.ts#L8-L14)
## Onion Model Execution with Compose
### Recursive Dispatch Loop Mechanics
The `compose` function structures middleware execution using an internal asynchronous `dispatch(i)` loop derived from the `koa-compose` package [src/compose.ts:5-32](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L5-L32). It accepts a `middleware` array of nested tuples, an optional `onError` handler, and an optional `onNotFound` handler, returning a function that executes the pipeline against an [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) instance [src/compose.ts:15-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L15-L19).
```typescript
export const compose = (
middleware: [[Function, unknown], unknown][] | [[Function]][],
onError?: ErrorHandler,
onNotFound?: NotFoundHandler
): ((context: Context, next?: Next) => Promise) => {
return (context, next) => {
let index = -1
return dispatch(0)
```
Sources: [src/compose.ts:15-24](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L15-L24)
Each invocation tracks index advancement through the `index` local variable [src/compose.ts:21-36](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L21-L36). If `dispatch(i)` is invoked with an index less than or equal to the current `index` marker, it immediately throws an error [src/compose.ts:33-35](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L33-L35). This guard prevents middleware from calling `next()` multiple times within the same execution cycle [src/compose.ts:33-35](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L33-L35).
> [!WARNING]
> Calling `next()` more than once within a single middleware layer triggers an immediate `Error` with the message `'next() called multiple times'` due to the `i <= index` check in the `dispatch` loop.
Sources: [src/compose.ts:33-35](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L33-L35)
### Pipeline Resolution and Handler Invocation
When a middleware item exists at the current index `i`, `dispatch` extracts the handler function from `middleware[i][0][0]` and updates `context.req.routeIndex` to match the current execution index [src/compose.ts:42-44](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L42-L44). When `i` reaches the end of the middleware array (`i === middleware.length`), the dispatcher checks for an outer `next` function [src/compose.ts:45-47](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L45-L47).
```typescript
if (middleware[i]) {
handler = middleware[i][0][0]
context.req.routeIndex = i
} else {
handler = (i === middleware.length && next) || undefined
}
```
Sources: [src/compose.ts:42-48](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L42-L48)
If a `handler` is resolved, it is executed within a `try...catch` block, passing `context` and a continuation callback `() => dispatch(i + 1)` [src/compose.ts:49-51](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L49-L51). If an error is thrown during handler execution and an `onError` function is provided, `context.error` is assigned the error, `onError` is invoked, and `isError` is set to `true` [src/compose.ts:52-56](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L52-L56). If no `onError` handler is present, the error is rethrown [src/compose.ts:57-59](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L57-L59).
```typescript
if (handler) {
try {
res = await handler(context, () => dispatch(i + 1))
} catch (err) {
if (err instanceof Error && onError) {
context.error = err
res = await onError(err, context)
isError = true
} else {
throw err
}
}
} else {
if (context.finalized === false && onNotFound) {
res = await onNotFound(context)
}
}
```
Sources: [src/compose.ts:49-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L49-L65)
When no handler is found and the response has not been finalized (`context.finalized === false`), an optional `onNotFound` handler is executed [src/compose.ts:61-64](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L61-L64). Finally, if a response `res` is returned and either the response is unfinalized or an error occurred, `context.res` is updated with `res`, and the `context` is returned [src/compose.ts:67-70](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L67-L70).
Sources: [src/compose.ts:67-70](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L67-L70)
## Conditional Routing with Combine Middleware
### Conditional Composition Helpers
The combine middleware module provides advanced flow-control helpers (`some`, `every`, and `except`) that evaluate middleware arrays based on boolean condition functions or path pattern strings [src/middleware/combine/index.ts:38-165](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L165). These functions inspect the Execution Context or intercept continuation calls to conditionally bypass or enforce middleware execution [src/middleware/combine/index.ts:38-165](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L165).
```typescript
export const some = (...middleware: (MiddlewareHandler | Condition)[]): MiddlewareHandler => {
return async function some(c, next) {
let isNextCalled = false
const wrappedNext = () => {
isNextCalled = true
return next()
}
let lastError: unknown
for (const handler of middleware) {
try {
const result = await handler(c, wrappedNext)
if (result === true && !c.finalized) {
await wrappedNext()
} else if (result === false) {
lastError = new Error('No successful middleware found')
continue
}
lastError = undefined
break
} catch (error) {
lastError = error
if (isNextCalled) {
break
}
}
}
if (lastError) {
throw lastError
}
}
}
```
Sources: [src/middleware/combine/index.ts:38-69](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L69)
The `some` helper iterates over an array of middleware or condition functions sequentially [src/middleware/combine/index.ts:38-47](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L47). If a handler returns `true` and the context is not finalized, it invokes `wrappedNext()` to proceed, halting subsequent evaluation upon the first successful or non-error exit [src/middleware/combine/index.ts:47-57](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L47-L57). If a handler returns `false`, it records a new `Error('No successful middleware found')` and continues [src/middleware/combine/index.ts:52-55](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L52-L55).
```typescript
export const every = (...middleware: (MiddlewareHandler | Condition)[]): MiddlewareHandler => {
return async function every(c, next) {
const currentRouteIndex = c.req.routeIndex
await compose(
middleware.map((m) => [
[
async (c: Context, next: Next) => {
c.req.routeIndex = currentRouteIndex // should be unchanged in this context
const res = await m(c, next)
if (res === false) {
throw new Error('Unmet condition')
}
return res
},
],
])
)(c, next)
}
}
```
Sources: [src/middleware/combine/index.ts:99-117](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L99-L117)
The `every` helper wraps all provided middleware items inside a `compose` pipeline [src/middleware/combine/index.ts:99-115](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L99-L115). It preserves `c.req.routeIndex` across individual wrapped executions and throws an `Error('Unmet condition')` if any inner handler returns `false` [src/middleware/combine/index.ts:101-111](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L101-L111).
> [!NOTE]
> The `every` helper explicitly resets `c.req.routeIndex` to the parent route index inside each wrapped handler to ensure consistent route index tracking during composite pipeline execution.
Sources: [src/middleware/combine/index.ts:101-106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L101-L106)
### Path Pattern Matching and Execution Walkthrough
The `except` helper accepts condition specifiers that can be strings, condition functions, or arrays of both [src/middleware/combine/index.ts:141-146](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L141-L146). String patterns are added to a private `TrieRouter` instance using `METHOD_NAME_ALL`, while condition functions are collected directly into an evaluation array [src/middleware/combine/index.ts:145-155](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L145-L155). If a router was initialized, an additional condition is prepended that checks if `router.match(METHOD_NAME_ALL, c.req.path)` successfully resolves [src/middleware/combine/index.ts:149-159](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L157-L159).
```typescript
export const except = (
condition: string | Condition | (string | Condition)[],
...middleware: MiddlewareHandler[]
): MiddlewareHandler => {
let router: TrieRouter | undefined = undefined
const conditions = (Array.isArray(condition) ? condition : [condition])
.map((condition) => {
if (typeof condition === 'string') {
router ||= new TrieRouter()
router.add(METHOD_NAME_ALL, condition, true)
} else {
return condition
}
})
.filter(Boolean) as Condition[]
if (router) {
conditions.unshift((c: Context) => !!router?.match(METHOD_NAME_ALL, c.req.path)?.[0]?.[0]?.[0])
}
const handler = some((c: Context) => conditions.some((cond) => cond(c)), every(...middleware))
return async function except(c, next) {
await handler(c, next)
}
}
```
Sources: [src/middleware/combine/index.ts:141-165](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L141-L165)
When an incoming request reaches an `except` middleware combination, execution flows through a precise sequence of internal helper calls before dispatching [src/middleware/combine/index.ts:161-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L161-L164).
1. `except` evaluates path conditions and constructs a composite handler via `some` and `every` [src/middleware/combine/index.ts:161-162](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L161-L162).
2. `handler` executes the `some` wrapper logic to test whether the exclusion condition matches the context [src/middleware/combine/index.ts:39-68](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L39-L68).
3. `every` maps the remaining middleware array into individual wrapped handlers that enforce boolean checks [src/middleware/combine/index.ts:102-114](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L102-L114).
4. `compose` aggregates the mapped middleware items into a linear execution array [src/compose.ts:15-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L15-L19).
5. `dispatch` recursively steps through index `i` to execute each middleware layer in the onion pipeline [src/compose.ts:32-71](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L32-L71).
```mermaid
sequenceDiagram
participant Except as src/middleware/combine/index.ts (except)
participant Handler as src/middleware/combine/index.ts (some)
participant Every as src/middleware/combine/index.ts (every)
participant Compose as src/compose.ts (compose)
participant Dispatch as src/compose.ts (dispatch)
Except->>Handler: constructs conditional handler via some
Handler->>Every: executes alternate branch via every
Every->>Compose: wraps middleware array with compose
Compose->>Dispatch: initiates recursive dispatch(0) loop
```
Sources: [src/compose.ts:15-71](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L15-L71), [src/middleware/combine/index.ts:39-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L39-L164)
## Short-Circuiting and Wrapped Execution
### Evaluation Tracing and Control Flow
When composite middleware runs, execution bypasses subsequent handlers or short-circuits depending on return values and exception states. The `some` implementation manages this flow by maintaining an `isNextCalled` flag and a `wrappedNext` closure that delegates directly to the underlying `next()` function [src/middleware/combine/index.ts:38-44](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L44).
```typescript
export const some = (...middleware: (MiddlewareHandler | Condition)[]): MiddlewareHandler => {
return async function some(c, next) {
let isNextCalled = false
const wrappedNext = () => {
isNextCalled = true
return next()
}
let lastError: unknown
for (const handler of middleware) {
try {
const result = await handler(c, wrappedNext)
if (result === true && !c.finalized) {
await wrappedNext()
} else if (result === false) {
lastError = new Error('No successful middleware found')
continue
}
lastError = undefined
break
} catch (error) {
lastError = error
if (isNextCalled) {
break
}
}
}
if (lastError) {
throw lastError
}
}
}
```
Sources: [src/middleware/combine/index.ts:38-69](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L69)
Incoming requests flow through a specific sequence of internal functions during short-circuiting operations [src/middleware/combine/index.ts:38-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L164).
1. `except` evaluates route path patterns and custom predicates [src/middleware/combine/index.ts:141-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L141-L164).
2. `handler` invokes the composed `some` wrapper [src/middleware/combine/index.ts:161-163](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L161-L163).
3. `some` iterates over its middleware arguments, calling each with `c` and `wrappedNext` [src/middleware/combine/index.ts:47-49](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L47-L49).
4. `wrappedNext` sets `isPreserved` flags or `isNextCalled` to `true` before triggering downstream execution [src/middleware/combine/index.ts:41-44](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L41-L44).
```mermaid
sequenceDiagram
participant Except as src/middleware/combine/index.ts (except)
participant Handler as src/middleware/combine/index.ts (handler)
participant Some as src/middleware/combine/index.ts (some)
participant WrappedNext as src/middleware/combine/index.ts (wrappedNext)
Except->>Handler: invokes wrapped composite handler
Handler->>Some: evaluates condition set in some
Some->>WrappedNext: triggers wrappedNext on match
WrappedNext->>WrappedNext: marks isNextCalled = true and invokes next()
```
Sources: [src/middleware/combine/index.ts:38-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L164)
> [!WARNING]
> If a handler inside `some` invokes `wrappedNext()` and subsequently throws an error, the catch block checks `isNextCalled`; if true, iteration breaks immediately to prevent duplicate error handling or redundant execution [src/middleware/combine/index.ts:58-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L58-L63).
Sources: [src/middleware/combine/index.ts:58-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L58-L63)
## Middleware Type Safety and Factory Helpers
### Factory Initialization and Middleware Typing
The `Factory` class and `createFactory` helper manage environment bindings (`Env`), route path types (`P`), and default application options when instantiating `Hono` apps [src/helper/factory/index.ts:332-366](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L332-L366).
```typescript
export class Factory {
private initApp?: InitApp
#defaultAppOptions?: HonoOptions
constructor(init?: { initApp?: InitApp; defaultAppOptions?: HonoOptions }) {
this.initApp = init?.initApp
this.#defaultAppOptions = init?.defaultAppOptions
}
createApp = (options?: HonoOptions): Hono => {
const app = new Hono(
options && this.#defaultAppOptions
? { ...this.#defaultAppOptions, ...options }
: (options ?? this.#defaultAppOptions)
)
if (this.initApp) {
this.initApp(app)
}
return app
}
```
Sources: [src/helper/factory/index.ts:332-351](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L332-L351)
> [!NOTE]
> The `Factory` constructor accepts an object with `initApp` and `defaultAppOptions`, which are merged during `createApp` execution to unify global middleware and configuration [src/helper/factory/index.ts:336-351](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L336-L351).
Sources: [src/helper/factory/index.ts:336-351](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L336-L351)
### Chained Handler Intersections
Chaining multiple handlers via factory definitions requires intersecting non-any environment types (`Env`) and input constraints (`Input`) across up to ten sequential parameters [src/helper/factory/index.ts:77-329](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L77-L329). Type parameters use `IntersectNonAnyTypes` to accumulate context extensions without polluting the base types [src/helper/factory/index.ts:88-92](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L88-L92).
| Generic Parameter | Base Type / Constraint | Purpose |
| :--- | :--- | :--- |
| `E` / `E2`–`E11` | `Env` | Environment binding accumulation across chained handlers |
| `I` / `I2`–`I10` | `Input` | Request input validation types and schema intersections |
| `R` / `R2`–`R10` | `HandlerResponse` | Return type validation for individual middleware steps |
| `P` | `string` | URL parameter matching string constraint |
Sources: [src/helper/factory/index.ts:77-329](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L77-L329)
## Handler Reflection and Middleware Inspection
### Introspecting Function Signatures and Target Handlers
Hono provides utility functions to inspect handler chains, distinguishing middleware from terminal route handlers by examining function argument lengths and unwrapping composed wrappers [src/utils/handler.ts:8-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/handler.ts#L8-L14). The `isMiddleware` helper checks whether a handler function expects multiple parameters, corresponding to the `(c, next)` middleware signature [src/utils/handler.ts:8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/handler.ts#L8). The `findTargetHandler` utility recursively inspects composed handlers via the `COMPOSED_HANDLER` symbol to locate the underlying terminal or base handler [src/utils/handler.ts:9-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/handler.ts#L9-L14).
```typescript
export const isMiddleware = (handler: Function) => handler.length > 1
export const findTargetHandler = (handler: Function): Function => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (handler as any)[COMPOSED_HANDLER]
? // eslint-disable-next-line @typescript-eslint/no-explicit-any
findTargetHandler((handler as any)[COMPOSED_HANDLER])
: handler
```
Sources: [src/utils/handler.ts:8-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/handler.ts#L8-L14)
> [!NOTE]
> Because `isMiddleware` evaluates `handler.length > 1`, terminal handlers taking only the Context argument `(c)` return `false`, whereas middleware and wrapped handlers taking `(c, next)` return `true` [src/utils/handler.ts:8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/handler.ts#L8).
Sources: [src/utils/handler.ts:8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/handler.ts#L8)
## Related
- [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core)
- [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context)
---
## Technical docs: Presets and Builds
URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/presets-and-builds
Relevant source files
The following files were used as context for generating this wiki page:
- [src/preset/quick.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts)
- [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json)
- [src/preset/tiny.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts)
- [src/middleware/compress/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts)
- [src/helper/ssg/ssg.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/ssg.ts)
- [jsr.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json)
- [src/middleware/jsx-renderer/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts)
- [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts)
- [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts)
- [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts)
- [src/middleware/cache/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts)
- [src/helper/adapter/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts)
- [runtime-tests/deno-jsx/deno.precompile.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/deno-jsx/deno.precompile.json)
- [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts)
- [src/hono.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono.ts)
- [src/helper/ssg/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/index.ts)
- [src/helper/proxy/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts)
- [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts)
- [perf-measures/bundle-check/scripts/check-bundle-size.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts)
- [src/middleware/pretty-json/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/pretty-json/index.ts)
- [src/helper/css/common.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/css/common.ts)
- [src/router/linear-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/index.ts)
- [src/middleware/serve-static/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/serve-static/index.ts)
- [src/adapter/netlify/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/index.ts)
- [src/middleware/body-limit/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts)
- [src/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts)
- [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts)
- [runtime-tests/deno/deno.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/deno/deno.json)
- [src/helper/accepts/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/accepts/index.ts)
- [src/router/reg-exp-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/index.ts)
## Overview
The presets and builds system provides specialized distribution bundles, entry points, and routing optimizations tailored for different runtime performance characteristics and footprint constraints. Hono delivers standard functionality through its core router composition while offering lightweight distribution presets such as `[[Application Core]]` routing alternatives, package export mappings across `package.json` and `jsr.json`, and automated bundle size auditing harnesses [[src/preset/quick.ts:1-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L1-L23), [[package.json:37-67](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L37-L67), [[src/preset/tiny.ts:1-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L1-L19), [[jsr.json:8-106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L8-L106), [perf-measures/bundle-check/scripts/check-bundle-size.ts:1-50](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L1-L50). Sources: [src/preset/quick.ts:1-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L1-L23), [package.json:37-67](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L37-L67), [src/preset/tiny.ts:1-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L1-L19), [jsr.json:8-106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L8-L106), [perf-measures/bundle-check/scripts/check-bundle-size.ts:1-50](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L1-L50)
## Preset Architecture and Entry Points
### Specialized Distribution Entry Points
Hono exposes multiple public distribution entry points designed for different runtime environments, bundle size thresholds, and routing performance profiles. The standard entry point at `.` resolves to the main package distribution, while specialized preset modules such as `[[Application Core]]` routing bundles target restricted environments [package.json:37-67](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L37-L67), [jsr.json:8-106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L8-L106).
Hono organizes its distribution bundles across standard CommonJS, ESM, and type definition outputs defined in `package.json` and registry manifests in `jsr.json`. Consumers can import specialized presets directly from subpaths such as `./quick` and `./tiny` to optimize their application build output [package.json:37-67](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L37-L67), [jsr.json:8-106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L8-L106).
| Export Subpath | Type Definitions | ESM Output | CommonJS Output | Preset Purpose |
| -------------- | ---------------- | ---------- | --------------- | -------------- |
| `.` | `./dist/types/index.d.ts` | `./dist/index.js` | `./dist/cjs/index.js` | Standard multi-router entry point |
| `./quick` | `./dist/types/preset/quick.d.ts` | `./dist/preset/quick.js` | `./dist/cjs/preset/quick.js` | `[[Application Core]]` with `SmartRouter` (Linear + Trie) |
| `./tiny` | `./dist/types/preset/tiny.d.ts` | `./dist/preset/tiny.js` | `./dist/cjs/preset/tiny.js` | `[[Application Core]]` with lightweight `PatternRouter` |
Sources: [package.json:37-67](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L37-L67), [jsr.json:8-106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L8-L106)
### Architectural Trade-Offs
The standard package entry point imports from `./hono`, allowing developers to leverage comprehensive feature sets across middlewares and helpers [src/index.ts:17-53](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts#L17-L53). In contrast, specialized presets bypass default router selections by extending `HonoBase` directly with targeted routing engines [src/preset/quick.ts:6-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L6-L23), [src/preset/tiny.ts:6-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L6-L19).
> [!NOTE]
> The `hono/quick` preset initializes a `SmartRouter` composed of `LinearRouter` and `TrieRouter` instances, whereas `hono/tiny` instantiates a single `PatternRouter` to minimize initialization overhead [src/preset/quick.ts:20-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L20-L22), [src/preset/tiny.ts:18-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L18-L18).
Sources: [src/preset/quick.ts:6-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L6-L23), [src/preset/tiny.ts:6-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L6-L19), [src/index.ts:17-53](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts#L17-L53)
## Quick Preset Router Composition
### Smart Router Initialization and Composition
The `hono/quick` preset constructs an optimized subclass of `[[Application Core]]` by extending `HonoBase` and instantiating a `SmartRouter` within its constructor [src/preset/quick.ts:13-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L13-L23). Rather than binding to a single routing strategy, `SmartRouter` receives an array containing both a `LinearRouter` and a `TrieRouter` instance [src/preset/quick.ts:20-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L20-L22).
```typescript
export class Hono<
E extends Env = BlankEnv,
S extends Schema = BlankSchema,
BasePath extends string = '/',
> extends HonoBase {
constructor(options: HonoOptions = {}) {
super(options)
this.router = new SmartRouter({
routers: [new LinearRouter(), new TrieRouter()],
})
}
```
Sources: [src/preset/quick.ts:13-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L13-L23)
> [!NOTE]
> The `hono/quick` preset relies on module resolution from `../router/linear-router`, `../router/smart-router`, and `../router/trie-router` to assemble its multi-strategy matching engine [src/preset/quick.ts:8-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L8-L10).
Sources: [src/preset/quick.ts:8-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L8-L10)
### Fallback Mechanics and Execution Flow
| Component Class | Import Path | Role in `SmartRouter` Composition |
| --------------- | ----------- | --------------------------------- |
| `LinearRouter` | `../router/linear-router` | Fast linear scanning for simpler route tables [src/preset/quick.ts:8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L8), [src/preset/quick.ts:21](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L21) |
| `TrieRouter` | `../router/trie-router` | Prefix tree matching for complex parameter patterns [src/preset/quick.ts:10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L10), [src/preset/quick.ts:21](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L21) |
| `SmartRouter` | `../router/smart-router` | Composite wrapper managing router selection and fallback [src/preset/quick.ts:9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L9), [src/preset/quick.ts:20-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L20-L22) |
Sources: [src/preset/quick.ts:8-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L8-L10), [src/preset/quick.ts:20-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L20-L22)
## Tiny Preset for Constrained Runtimes
### Pattern-Based Dispatch Mechanics
The `hono/tiny` preset configures a minimal application footprint by extending `HonoBase` with the lightweight `PatternRouter` engine [src/preset/tiny.ts:6-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L6-L19). Instantiating `Hono` within this module assigns a `PatternRouter` directly to `this.router`, omitting complex multi-router selection logic and reducing overall binary weight for constrained execution environments [src/preset/tiny.ts:16-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L16-L19).
```typescript
export class Hono<
E extends Env = BlankEnv,
S extends Schema = BlankSchema,
BasePath extends string = '/',
> extends HonoBase {
constructor(options: HonoOptions = {}) {
super(options)
this.router = new PatternRouter()
}
}
```
Sources: [src/preset/tiny.ts:11-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L11-L20)]
> [!NOTE]
> The `hono/tiny` implementation accepts generic type parameters for environment bindings (`Env`), schema validation (`Schema`), and base path prefixes (`BasePath`), passing options directly to the `HonoBase` superclass constructor [src/preset/tiny.ts:11-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L11-L17).
Sources: [src/preset/tiny.ts:11-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L11-L17)
### Class and Type Configuration
| Exported Symbol | Source Path | Type Definition / Role |
| --------------- | ----------- | ---------------------- |
| `Hono` | `src/preset/tiny.ts` | Subclass of `HonoBase` enforcing `PatternRouter` [src/preset/tiny.ts:6-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L6-L19) |
| `HonoBase` | `../hono-base` | Core routing and middleware execution engine [src/preset/tiny.ts:6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L6), [src/preset/tiny.ts:15](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L15) |
| `PatternRouter` | `../router/pattern-router` | Lightweight pattern-matching router backend [src/preset/tiny.ts:8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L8), [src/preset/tiny.ts:18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L18) |
| `HonoOptions` | `../hono-base` | Configuration options interface for instantiation [src/preset/tiny.ts:7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L7), [src/preset/tiny.ts:16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L16) |
Sources: [src/preset/tiny.ts:6-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L6-L19)]
## Package Export Maps and Module Resolution
### Node.js Package Configuration and Conditional Exports
The `package.json` file establishes dual CommonJS and ES Module distribution channels alongside TypeScript declaration mappings [package.json:5-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L5-L8), [package.json:37-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L37-L42). The root export configuration maps types, ESM imports, and CommonJS requires for core modules, presets, middleware, helpers, and utilities [package.json:37-144](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L37-L144).
| Export Key | Types Path | Import Path (ESM) | Require Path (CJS) |
| ---------- | ---------- | ----------------- | ------------------ |
| `.` | `./dist/types/index.d.ts` [package.json:39](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L39) | `./dist/index.js` [package.json:40](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L40) | `./dist/cjs/index.js` [package.json:41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L41) |
| `./request` | `./dist/types/request.d.ts` [package.json:44](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L44) | `./dist/request.js` [package.json:45](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L45) | `./dist/cjs/request.js` [package.json:46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L46) |
| `./tiny` | `./dist/types/preset/tiny.d.ts` [package.json:59](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L59) | `./dist/preset/tiny.js` [package.json:60](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L60) | `./dist/cjs/preset/tiny.js` [package.json:61](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L61) |
| `./quick` | `./dist/types/preset/quick.d.ts` [package.json:64](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L64) | `./dist/preset/quick.js` [package.json:65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L65) | `./dist/cjs/preset/quick.js` [package.json:66](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L66) |
| `./compress` | `./dist/types/middleware/compress/index.d.ts` [package.json:114](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L114) | `./dist/middleware/compress/index.js` [package.json:115](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L115) | `./dist/cjs/middleware/compress/index.js` [package.json:116](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L116) |
Sources: [package.json:37-117](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L37-L117)
> [!NOTE]
> The postbuild script executes `publint` to validate export map correctness, and copies `package.cjs.json` into distribution subdirectories to enforce CommonJS resolution boundaries [package.json:28-30](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L28-L30).
Sources: [package.json:28-30](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L28-L30)
### JSR and Deno Module Resolution
The `jsr.json` manifest defines direct TypeScript source mappings for JSR distribution, targeting Deno and modern edge runtimes [jsr.json:1-106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L1-L106). It enables the `sloppy-imports` unstable flag and specifies compiler options tailored for DOM and Deno namespaces [jsr.json:4-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L4-L7).
```json
"exports": {
".": "./src/index.ts",
"./request": "./src/request.ts",
"./types": "./src/types.ts",
"./hono-base": "./src/hono-base.ts",
"./tiny": "./src/preset/tiny.ts",
"./quick": "./src/preset/quick.ts",
"./http-exception": "./src/http-exception.ts",
"./basic-auth": "./src/middleware/basic-auth/index.ts",
"./bearer-auth": "./src/middleware/bearer-auth/index.ts",
"./body-limit": "./src/middleware/body-limit/index.ts",
"./ip-restriction": "./src/middleware/ip-restriction/index.ts",
"./cache": "./src/middleware/cache/index.ts",
"./route": "./src/helper/route/index.ts",
"./cookie": "./src/helper/cookie/index.ts",
"./accepts": "./src/helper/accepts/index.ts",
"./compress": "./src/middleware/compress/index.ts",
"./context-storage": "./src/middleware/context-storage/index.ts",
"./cors": "./src/middleware/cors/index.ts",
"./csrf": "./src/middleware/csrf/index.ts",
"./etag": "./src/middleware/etag/index.ts",
"./trailing-slash": "./src/middleware/trailing-slash/index.ts",
"./html": "./src/helper/html/index.ts",
"./css": "./src/helper/css/index.ts",
"./jsx": "./src/jsx/index.ts",
"./jsx/jsx-dev-runtime": "./src/jsx/jsx-dev-runtime.ts",
"./jsx/jsx-runtime": "./src/jsx/jsx-runtime.ts",
"./jsx/streaming": "./src/jsx/streaming.ts",
"./jsx-renderer": "./src/middleware/jsx-renderer/index.ts",
```
Sources: [jsr.json:8-36](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L8-L36)
Publish configuration within `jsr.json` explicitly includes source files, configuration manifests, and documentation while excluding test files [jsr.json:107-110](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L107-L110). Runtime test configurations like `runtime-tests/deno/deno.json` bind [JSX runtime](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/jsx-runtime) imports to local source files and configure standard library dependencies [runtime-tests/deno/deno.json:1-13](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/deno/deno.json#L1-L13).
Sources: [jsr.json:107-110](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L107-L110), [runtime-tests/deno/deno.json:1-13](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/deno/deno.json#L1-L13)]
## Bundle Size Auditing and Enforcement
To prevent performance regressions and maintain minimal footprints across core distribution files, Hono uses an automated bundle measurement harness driven by `esbuild`. The check script compiles the built entry point `dist/index.js` into an isolated temporary file using production settings, extracts exact byte and kilobyte measurements, and outputs structured benchmark JSON for validation pipelines.
```typescript
async function main() {
const tempDir = os.tmpdir()
const tempFilePath = path.join(tempDir, 'bundle.tmp.js')
try {
await esbuild.build({
entryPoints: ['dist/index.js'],
bundle: true,
minify: true,
format: 'esm' as esbuild.Format,
target: 'es2022',
outfile: tempFilePath,
})
const bundleSize = fs.statSync(tempFilePath).size
const metrics = []
```
Sources: [perf-measures/bundle-check/scripts/check-bundle-size.ts:6-21](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L6-L21)
| Configuration Property | Target Value | Purpose |
| ---------------------- | ------------ | ------- |
| `entryPoints` | `['dist/index.js']` | Specifies the compiled core bundle input file [perf-measures/bundle-check/scripts/check-bundle-size.ts:12](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L12) |
| `bundle` | `true` | Resolves and inlines all internal module dependencies [perf-measures/bundle-check/scripts/check-bundle-size.ts:13](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L13) |
| `minify` | `true` | Strips whitespace and mangles identifiers to measure production delivery size [perf-measures/bundle-check/scripts/check-bundle-size.ts:14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L14) |
| `format` | `'esm'` | Enforces ECMAScript module output format [perf-measures/bundle-check/scripts/check-bundle-size.ts:15](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L15) |
| `target` | `'es2022'` | Sets the JavaScript language syntax target level [perf-measures/bundle-check/scripts/check-bundle-size.ts:16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L16) |
| `outfile` | `tempFilePath` | Writes output to an OS temporary directory path [perf-measures/bundle-check/scripts/check-bundle-size.ts:17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L17) |
Sources: [perf-measures/bundle-check/scripts/check-bundle-size.ts:11-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L11-L18)
> [!WARNING]
> The auditing harness guarantees cleanup by executing file deletion inside a `finally` block, ensuring temporary artifacts are wiped even if the compilation pass encounters errors [perf-measures/bundle-check/scripts/check-bundle-size.ts:45-49](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L45-L49).
Sources: [perf-measures/bundle-check/scripts/check-bundle-size.ts:45-49](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L45-L49)]
## Related
- [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core)
- [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts)
---
## Technical docs: Router Contracts
URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts
Relevant source files
The following files were used as context for generating this wiki page:
- [src/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts)
- [src/router/linear-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts)
- [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts)
- [src/router/pattern-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts)
- [src/router/reg-exp-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts)
- [src/router/reg-exp-router/matcher.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts)
- [src/helper/route/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts)
- [src/router/reg-exp-router/prepared-router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts)
- [src/router/trie-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts)
- [src/router/trie-router/node.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts)
- [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts)
- [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts)
- [src/router/smart-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts)
- [src/utils/url.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts)
- [src/router/reg-exp-router/trie.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts)
- [src/router/reg-exp-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/index.ts)
- [src/router/pattern-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/index.ts)
- [src/router/trie-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/index.ts)
## Overview
Hono defines a generic Router Contracts through the `Router` interface, standardizing how route registration and execution path resolution behave across multiple routing backends [Linear and Pattern Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/linear-and-pattern-routers), [RegExp Router](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/regexp-router), and [Trie and Smart Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/trie-and-smart-routers). By establishing uniform method signatures for adding paths and matching request methods against registered endpoints, the system allows backends like `LinearRouter`, `PatternRouter`, `RegExpRouter`, and `TrieRouter` to be swapped interchangeably inside applications ([Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core)). These contracts establish strict behaviors around immutable matchers and path constraints, such as throwing `UnsupportedPathError` when conflicting route syntaxes occur during compilation or evaluation.
Sources: [src/router.ts:25-52](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L25-L52), [src/router.ts:101-103](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L101-L103), [src/router/linear-router/router.ts:11-143](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L11-L143), [src/router/pattern-router/router.ts:8-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L8-L42), [src/router/reg-exp-router/router.ts:122-204](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L122-L204), [src/router/trie-router/router.ts:5-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts#L5-L27), [src/router/smart-router/router.ts:4-61](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L4-L61), [src/hono-base.ts:65-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L65-L65)
## Unified Router Interface Architecture
### Router Interface Contract
The generic `Router` interface establishes the core contract that every routing backend implements. It defines three primary members: a `name` string property identifying the router implementation, an `add` method for registering paths, and a `match` method for executing lookups.
```typescript
* Interface representing a router.
*
* @template T - The type of the handler.
*/
export interface Router {
/**
* The name of the router.
*/
name: string
/**
* Adds a route to the router.
*
* @param method - The HTTP method (e.g., 'get', 'post').
* @param path - The path for the route.
* @param handler - The handler for the route.
*/
add(method: string, path: string, handler: T): void
/**
* Matches a route based on the given method and path.
*
* @param method - The HTTP method (e.g., 'get', 'post').
* @param path - The path to match.
* @returns The result of the match.
*/
match(method: string, path: string): Result
}
```
Sources: [src/router.ts:25-52](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L25-L52)
To support this interface uniformly, the module exports constants defining HTTP methods and error messages utilized during route registration and compilation checks.
```typescript
* Constant representing all HTTP methods in uppercase.
*/
export const METHOD_NAME_ALL = 'ALL' as const
/**
* Constant representing all HTTP methods in lowercase.
*/
export const METHOD_NAME_ALL_LOWERCASE = 'all' as const
/**
* Array of supported HTTP methods.
*/
export const METHODS = ['get', 'post', 'put', 'delete', 'options', 'patch'] as const
/**
* Error message indicating that a route cannot be added because the matcher is already built.
*/
export const MESSAGE_MATCHER_IS_ALREADY_BUILT =
'Can not add a route since the matcher is already built.'
```
Sources: [src/router.ts:7-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L7-L23)
> [!NOTE]
> The `METHOD_NAME_ALL` and `METHOD_NAME_ALL_LOWERCASE` constants represent wildcard HTTP methods ('ALL' and 'all') used to register handlers matching any incoming request method.
### Interface Implementation Registry
Different routing strategies fulfill the `Router` contract across the codebase, exporting their constructors or helper utilities from respective entrypoints.
| Router Module | Exported Symbols | Description |
| :--- | :--- | :--- |
| `src/router/reg-exp-router/index.ts` | `RegExpRouter`, `PreparedRegExpRouter`, `buildInitParams`, `serializeInitParams` | Compiles route trees into single regular expressions |
| `src/router/pattern-router/index.ts` | `PatternRouter` | Evaluates basic pattern matching for lightweight requirements |
| `src/router/trie-router/index.ts` | `TrieRouter` | Traverses path segments using node trees |
```typescript
/**
* @module
* RegExpRouter for Hono.
*/
export { RegExpRouter } from './router'
export { PreparedRegExpRouter, buildInitParams, serializeInitParams } from './prepared-router'
```
Sources: [src/router/reg-exp-router/index.ts:1-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/index.ts#L1-L7)
```typescript
/**
* @module
* PatternRouter for Hono.
*/
```
Sources: [src/router/pattern-router/index.ts:1-5](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/index.ts#L1-L5)
```typescript
/**
* @module
* TrieRouter for Hono.
*/
export { TrieRouter } from './router'
```
Sources: [src/router/trie-router/index.ts:1-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/index.ts#L1-L6)
## Match Result Representations and Parameter Extraction
### Result Data Tuples and Parameter Formats
Route resolution yields a `Result` tuple that accommodates two distinct structural layouts depending on the underlying router implementation. Each format pairs matched handlers with parameter mappings or value stashes.
```typescript
* Type representing a map of parameter indices.
*/
export type ParamIndexMap = Record
/**
* Type representing a stash of parameters.
*/
export type ParamStash = string[]
/**
* Type representing a map of parameters.
*/
export type Params = Record
/**
* Type representing the result of a route match.
*
* The result can be in one of two formats:
* 1. An array of handlers with their corresponding parameter index maps, followed by a parameter stash.
* 2. An array of handlers with their corresponding parameter maps.
*
* Example:
*
* [[handler, paramIndexMap][], paramArray]
* ```typescript
* [
* [
* [middlewareA, {}], // '*'
* [funcA, {'id': 0}], // '/user/:id/*'
* [funcB, {'id': 0, 'action': 1}], // '/user/:id/:action'
* ],
* ['123', 'abc']
* ]
* ```
*
* [[handler, params][]]
* ```typescript
* [
* [
* [middlewareA, {}], // '*'
* [funcA, {'id': '123'}], // '/user/:id/*'
* [funcB, {'id': '123', 'action': 'abc'}], // '/user/:id/:action'
* ]
* ]
* ```
*/
export type Result = [[T, ParamIndexMap][], ParamStash] | [[T, Params][]]
```
Sources: [src/router.ts:55-99](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L55-L99)
> [!NOTE]
> The first format nests a tuple of `[T, ParamIndexMap][]` alongside a separate `ParamStash` array (`string[]`), allowing parameter values to be indexed numerically. The second format directly associates handlers with fully resolved `Params` dictionaries (`Record`).
### Parameter Data Structures
Parameter management relies on specific type definitions for maps and value arrays. The module defines three distinct type aliases to support parameter extraction during route resolution.
| Type Name | Definition | Description |
| :--- | :--- | :--- |
| `ParamIndexMap` | `Record` | Maps parameter name keys to numeric index positions within the parameter stash array. |
| `ParamStash` | `string[]` | Ordered array of extracted string parameter values referenced by index maps. |
| `Params` | `Record` | Key-value dictionary mapping parameter names directly to their resolved string values. |
```typescript
* Type representing a map of parameter indices.
*/
export type ParamIndexMap = Record
/**
* Type representing a stash of parameters.
*/
export type ParamStash = string[]
/**
* Type representing a map of parameters.
*/
export type Params = Record
```
Sources: [src/router.ts:55-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L55-L65)
## Shared Routing Errors and Matcher Constraints
### Matcher State Invariants and Error Messages
During router lifecycle management, route addition is restricted once matching structures have been compiled or initialized. The module defines a specific constant error message to indicate this constraint violation when attempting modifications after compilation.
```typescript
* Error message indicating that a route cannot be added because the matcher is already built.
*/
export const MESSAGE_MATCHER_IS_ALREADY_BUILT =
'Can not add a route since the matcher is already built.'
```
Sources: [src/router.ts:19-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L19-L23)
> [!WARNING]
> Attempting to invoke `add` after a router implementation has built its matcher triggers the error message defined by `MESSAGE_MATCHER_IS_ALREADY_BUILT`, freezing route registration to ensure thread-safe and deterministic lookups.
### Unsupported Path Error Semantics
When path structures fail validation or fall outside supported syntax patterns during registration or matching, routers throw specialized error types extending standard JavaScript exceptions.
```typescript
/**
* Error class representing an unsupported path error.
*/
export class UnsupportedPathError extends Error {}
```
Sources: [src/router.ts:100-103](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L100-L103)
| Error Class / Constant | Underlying Value / Base | Purpose |
| :--- | :--- | :--- |
| `UnsupportedPathError` | `Error` | Signals that a given route path contains unsupported tokens or structural formatting incompatible with the router backend. |
| `MESSAGE_MATCHER_IS_ALREADY_BUILT` | `'Can not add a route since the matcher is already built.'` | Prevents post-initialization mutation of router route tables. |
```typescript
export const MESSAGE_MATCHER_IS_ALREADY_BUILT =
'Can not add a route since the matcher is already built.'
…
*/
```
Sources: [src/router.ts:21-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L21-L22), [src/router.ts:102-102](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L102-L102)
## Route Introspection and Base Path Resolution
### Introspection Helpers and Active Route Selection
The routing helper module provides functions to inspect active request contexts and extract matching route metadata. The `matchedRoutes` function accesses the low-level match result stored on the request object using the `GET_MATCH_RESULT` constant symbol, mapping the internal tuple structure to an array of `RouterRoute` definitions.
```typescript
export const matchedRoutes = (c: Context): RouterRoute[] =>
// @ts-expect-error c.req[GET_MATCH_RESULT] is not typed
(c.req as unknown)[GET_MATCH_RESULT][0].map(([[, route]]) => route)
```
Sources: [src/helper/route/index.ts:32-34](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L32-L34)
```typescript
export const routePath = (c: Context, index?: number): string =>
matchedRoutes(c).at(index ?? c.req.routeIndex)?.path ?? ''
```
Sources: [src/helper/route/index.ts:58-59](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L58-L59)
> [!NOTE]
> Both `routePath` and `baseRoutePath` accept an optional index argument. This parameter behaves similarly to `Array.prototype.at()`, allowing negative integers to count backward from the end of the matching root collection while defaulting to `c.req.routeIndex`.
```typescript
export const baseRoutePath = (c: Context, index?: number): string =>
matchedRoutes(c).at(index ?? c.req.routeIndex)?.basePath ?? ''
```
Sources: [src/helper/route/index.ts:82-83](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L82-L83)
### Base Path Resolution and Caching
The `basePath` function computes the concrete base path with embedded parameters resolved against the active request URL. It utilizes a private `WeakMap` cache named `basePathCacheMap` to store calculated base paths per `Context` instance and index, avoiding redundant substring matching operations during nested application dispatches.
```typescript
const basePathCacheMap: WeakMap> = new WeakMap()
export const basePath = (c: Context, index?: number): string => {
index ??= c.req.routeIndex
const cache = basePathCacheMap.get(c) || []
if (typeof cache[index] === 'string') {
return cache[index]
}
```
Sources: [src/helper/route/index.ts:106-113](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L106-L113)
When the unparsed base route path contains dynamic parameters or wildcards matching `[:*]`, `basePath` splits the path via `splitRoutingPath` and iterates over each segment. It queries pattern matchers using `getPattern` to extract substring lengths directly from `c.req.path`, assembling the final prefix dynamically.
Sources: [src/helper/route/index.ts:107-141](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L107-L141)
> [!WARNING]
> Bypassing index bounds or passing uninitialized request contexts to route introspection helpers will cause lookup failures against `GET_MATCH_RESULT`. Always invoke these utilities within active request handler flows or middleware layers where routing context has been fully established.
### Execution Walkthroughs
#### Trace Sequence
The resolution of active route paths proceeds through a structured sequence of helper calls.
1. `basePath` checks the `basePathCacheMap` cache using the context and index; on a cache miss, it invokes `baseRoutePath`.
2. `baseRoutePath` calls `matchedRoutes` to retrieve the active route list.
3. `matchedRoutes` reads `(c.req as unknown)[GET_MATCH_RESULT][0]` and maps the internal tuples to return `RouterRoute[]`.
```mermaid
sequenceDiagram
participant Context as Context (c)
participant Helper as src/helper/route/index.ts
participant Request as c.req
Context->>Helper: basePath(c, index)
Helper->>Helper: baseRoutePath(c, index)
Helper->>Helper: matchedRoutes(c)
Helper->>Request: access GET_MATCH_RESULT symbol
Request-->>Helper: return internal match result tuples
Helper-->>Context: return resolved path string
```
Sources: [src/helper/route/index.ts:32-34](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L32-L34), [src/helper/route/index.ts:82-83](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L82-L83), [src/helper/route/index.ts:107-116](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L107-L116)
## Path Tokenization for Route Group Matching
### Path Splitting and Group Extraction
The URL utility module manages route path normalization by tokenizing paths, extracting embedded parameter groups, and restoring them during route matching. The `splitRoutingPath` function coordinates this normalization process by first invoking `extractGroupsFromPath` on the raw route string.
```typescript
export const splitRoutingPath = (routePath: string): string[] => {
const { groups, path } = extractGroupsFromPath(routePath)
const paths = splitPath(path)
return replaceGroupMarks(paths, groups)
}
```
Sources: [src/utils/url.ts:16-21](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts#L16-L21)
The `extractGroupsFromPath` function scans the input path for bracketed expressions matching `/\{[^}]+\}/g`. For every discovered group, it generates a placeholder mark using the pattern `@${index}` and stores the pair in an array before returning the modified path string.
```typescript
const extractGroupsFromPath = (path: string): { groups: [string, string][]; path: string } => {
const groups: [string, string][] = []
path = path.replace(/\{[^}]+\}/g, (match, index) => {
const mark = `@${index}`
groups.push([mark, match])
return mark
})
return { groups, path }
}
```
Sources: [src/utils/url.ts:23-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts#L23-L33)
> [!NOTE]
> Parameter group extraction prevents forward-slash characters contained inside custom regex definitions (such as `{id:[0-9/]+}`) from breaking segment-based path splitting operations.
```typescript
export const splitPath = (path: string): string[] => {
const paths = path.split('/')
if (paths[0] === '') {
paths.shift()
}
return paths
}
```
Sources: [src/utils/url.ts:8-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts#L8-L14)
### Group Mark Replacement
Once the path is split into individual segments via `splitPath`, the `replaceGroupMarks` function iterates backward through the stored groups to substitute temporary placeholders with their original bracketed definitions.
```typescript
const replaceGroupMarks = (paths: string[], groups: [string, string][]): string[] => {
for (let i = groups.length - 1; i >= 0; i--) {
const [mark] = groups[i]
for (let j = paths.length - 1; j >= 0; j--) {
if (paths[j].includes(mark)) {
paths[j] = paths[j].replace(mark, groups[i][1])
break
}
}
}
return paths
}
```
Sources: [src/utils/url.ts:35-48](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts#L35-L48)
> [!WARNING]
> Modifying tokenized path arrays directly without running `replaceGroupMarks` will leave orphan `@index` markers intact, corrupting downstream route compilation in [RegExp Router](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/regexp-router) and [Trie and Smart Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/trie-and-smart-routers).
### Execution Walkthroughs
#### Trace Sequences
##### Extraction Trace
1. `basePath` calls `splitRoutingPath`.
2. `splitRoutingPath` calls `extractGroupsFromPath`.
3. `extractGroupsFromPath` matches bracketed expressions and populates the groups array.
```mermaid
sequenceDiagram
participant Helper as basePath
participant URLUtils as splitRoutingPath
participant Extractor as extractGroupsFromPath
Helper->>URLUtils: splitRoutingPath(rp)
URLUtils->>Extractor: extractGroupsFromPath(routePath)
Extractor-->>URLUtils: return { groups, path }
```
Sources: [src/helper/route/index.ts:120-120](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L120-L120), [src/utils/url.ts:16-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts#L16-L17), [src/utils/url.ts:23-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts#L23-L33)
##### Replacement Trace
1. `basePath` calls `splitRoutingPath`.
2. `splitRoutingPath` calls `splitPath` on the cleaned path string.
3. `splitRoutingPath` calls `replaceGroupMarks` to substitute temporary markers.
```mermaid
sequenceDiagram
participant Helper as basePath
participant URLUtils as splitRoutingPath
participant Replacer as replaceGroupMarks
Helper->>URLUtils: splitRoutingPath(rp)
URLUtils->>URLUtils: splitPath(path)
URLUtils->>Replacer: replaceGroupMarks(paths, groups)
Replacer-->>URLUtils: return normalized paths array
```
Sources: [src/helper/route/index.ts:120-120](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L120-L120), [src/utils/url.ts:16-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts#L16-L20), [src/utils/url.ts:35-48](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts#L35-L48)
## Related
- [RegExp Router](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/regexp-router)
- [Trie and Smart Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/trie-and-smart-routers)
- [Linear and Pattern Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/linear-and-pattern-routers)
---
## Technical docs: RegExp Router
URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/regexp-router
Relevant source files
The following files were used as context for generating this wiki page:
- [src/router/reg-exp-router/node.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts)
- [src/router/reg-exp-router/trie.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts)
- [src/router/reg-exp-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts)
- [src/router/reg-exp-router/prepared-router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts)
- [src/helper/route/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts)
- [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts)
- [src/router/reg-exp-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/index.ts)
- [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts)
- [src/router/linear-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts)
- [src/router/trie-router/node.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts)
- [src/router/reg-exp-router/matcher.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts)
- [src/preset/quick.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts)
- [src/router/trie-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts)
- [src/helper/ssg/ssg.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/ssg.ts)
- [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts)
- [src/hono.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono.ts)
- [src/utils/url.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts)
- [src/router/trie-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/index.ts)
- [src/router/pattern-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts)
- [src/router/pattern-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/index.ts)
- [src/helper/dev/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/dev/index.ts)
- [src/preset/tiny.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts)
- [src/router/linear-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/index.ts)
- [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts)
- [src/router/smart-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts)
- [src/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts)
- [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json)
- [src/router/smart-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts)
- [src/utils/compress.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/compress.ts)
## Overview
The `RegExpRouter` implements the unified [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts) interface by compiling registered path structures and HTTP method sets into a single optimized regular expression [src/router/reg-exp-router/router.ts:122-207](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L122-L207). Operating as a core backend option for [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core) via SmartRouter, it transforms wildcard patterns, path parameters, and static segments into a radix-style node trie that generates a unified matcher [src/router/reg-exp-router/router.ts:34-103](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L34-L103), [src/router/reg-exp-router/trie.ts:6-73](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L6-L73). By consolidating route evaluation, it avoids linear array scans during request dispatching [src/router/reg-exp-router/matcher.ts:10-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L10-L33). Additionally, `PreparedRegExpRouter` supports ahead-of-time serialization and pre-compilation patterns to eliminate runtime startup overhead [src/router/reg-exp-router/prepared-router.ts:9-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L9-L164).
Sources: [src/router/reg-exp-router/router.ts:34-207](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L34-L207), [src/router/reg-exp-router/trie.ts:6-73](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L6-L73), [src/router/reg-exp-router/matcher.ts:10-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L10-L33), [src/router/reg-exp-router/prepared-router.ts:9-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L9-L164)
## Architecture and Routing Model
### Public Router Implementation and State Management
The `RegExpRouter` class implements the [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts) interface, managing route registration and request matching state through private collections [src/router/reg-exp-router/router.ts:122-130](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L122-L130). During the initialization phase, the router constructs separate storage maps for middleware and terminal routes under the `ALL` HTTP method (METHOD_NAME_ALL) [src/router/reg-exp-router/router.ts:127-130](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L127-L130).
```typescript
export class RegExpRouter implements Router {
name: string = 'RegExpRouter'
#middleware?: Record[]>>
#routes?: Record[]>>
constructor() {
this.#middleware = { [METHOD_NAME_ALL]: Object.create(null) }
this.#routes = { [METHOD_NAME_ALL]: Object.create(null) }
}
// ...
}
```
Sources: [src/router/reg-exp-router/router.ts:122-130](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L122-L130)
> [!IMPORTANT]
> Once a match operation compiles the underlying regular expression, the `#middleware` and `#routes` internal maps become `undefined`. Any subsequent call to `add()` after building will throw an error with `MESSAGE_MATCHER_IS_ALREADY_BUILT`.
Sources: [src/router/reg-exp-router/router.ts:136-138](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L136-L138)
### Route Registration Lifecycle
The `add()` method populates internal HTTP method tables, handles optional parameters via `checkOptionalParameter`, and processes wildcard suffix patterns [src/router/reg-exp-router/router.ts:132-204](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L132-L204). When a new HTTP method is encountered for the first time, the router initializes its maps by copying existing entries registered under `ALL` [src/router/reg-exp-router/router.ts:140-147](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L140-L147).
| Internal Property / Parameter | Type | Purpose |
| :--- | :--- | :--- |
| `name` | `string` | Identifies the router backend as `'RegExpRouter'`. |
| `#middleware` | `Record[]>>` | Stores registered middleware paths grouped by HTTP method. |
| `#routes` | `Record[]>>` | Stores terminal route handlers grouped by HTTP method. |
| `METHOD_NAME_ALL` | `string` | Constant designating catch-all HTTP methods (`'ALL'`). |
| `nullMatcher` | `Matcher` | Fallback matcher for empty routing tables (`[/^$/, [], Object.create(null)]`). |
Sources: [src/router.ts:9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L9), [src/router/reg-exp-router/router.ts:17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L17), [src/router/reg-exp-router/router.ts:122-130](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L122-L130), [src/router/reg-exp-router/router.ts:140-147](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L140-L147)
Wildcard patterns ending in `*` are expanded and tested against existing route entries using cached regular expressions built via `buildWildcardRegExp` [src/router/reg-exp-router/router.ts:20-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L20-L28), [src/router/reg-exp-router/router.ts:155-186](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L155-L186).
```typescript
function buildWildcardRegExp(path: string): RegExp {
return (wildcardRegExpCache[path] ??= new RegExp(
path === '*'
? ''
: `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) =>
metaChar ? `\\${metaChar}` : '(?:|/.*)'
)}$`
))
}
```
Sources: [src/router/reg-exp-router/router.ts:20-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L20-L28)
### Matcher Compilation Workflow
When request matching occurs, `buildMatcherFromPreprocessedRoutes` sorts paths, separates static and dynamic segments, and delegates structural insertion to a `Trie` instance [src/router/reg-exp-router/router.ts:34-82](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L34-L82). Static paths are stored directly in a `staticMap` for O(1) lookups, while dynamic paths contribute to a consolidated regular expression [src/router/reg-exp-router/router.ts:43-82](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L43-L82).
```typescript
function buildMatcherFromPreprocessedRoutes(
routes: [string, HandlerWithMetadata[]][]
): Matcher {
const trie = new Trie()
const handlerData: HandlerData[] = []
if (routes.length === 0) {
return nullMatcher
}
```
Sources: [src/router/reg-exp-router/router.ts:34-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L34-L42)
> [!WARNING]
> Path insertions that conflict with structural constraints or invalid syntax throw a `PATH_ERROR`, which the router catches and re-throws as an `UnsupportedPathError`.
Sources: [src/router/reg-exp-router/router.ts:61-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L61-L65)
## Trie Intermediate Representation
### Path Tokenization and Group Preservation
The `Trie` class manages routing structures through a root `Node` instance and a shared context tracking variable indices (`varIndex`) [src/router/reg-exp-router/trie.ts:6-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L6-L8). When a route path is inserted, the `insert()` method first isolates bracketed custom regular expression groups (such as `:id{[0-9]+}`) by replacing them with temporary placeholder markers (`@\i`) [src/router/reg-exp-router/trie.ts:13-26](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L13-L26). It then tokenizes the modified path using a regular expression that matches named parameters (`:[^\/]+`), wildcard suffixes (`/\*$`), or individual characters, before restoring the original bracketed expressions into the correct token positions [src/router/reg-exp-router/trie.ts:33-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L33-L42).
```typescript
const groups: [string, string][] = [] // [mark, original string]
for (let i = 0; ; ) {
let replaced = false
path = path.replace(/\{[^}]+\}/g, (m) => {
const mark = `@\\${i}`
groups[i] = [mark, m]
i++
replaced = true
return mark
})
if (!replaced) {
break
}
}
```
Sources: [src/router/reg-exp-router/trie.ts:13-26](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L13-L26)
### Node Graph Insertion and Conflict Checks
The `Node` class recursively inserts token arrays into its `#children` record map [src/router/reg-exp-router/node.ts:45-133](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L45-L133). During insertion, tokens are evaluated to determine their pattern types—distinguishing between standalone wildcards (`*`), tail wildcards (`/*`), named parameters with custom expressions, common label patterns (`[^/]+`), and literal characters [src/router/reg-exp-router/node.ts:69-78](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L69-L78).
| Token / Pattern Type | Regular Expression String | Assigned Variable / Purpose |
| :--- | :--- | :--- |
| `*` (terminal) | `.*` (`ONLY_WILDCARD_REG_EXP_STR`) | Matches all trailing paths without capturing a parameter name. |
| `*` (non-terminal) | `[^/]+` (`LABEL_REG_EXP_STR`) | Acts as a generic path segment label. |
| `/*` | `(?:|/.*)` (`TAIL_WILDCARD_REG_EXP_STR`) | Matches an optional trailing slash followed by any path content. |
| `:label` | `[^/]+` (`LABEL_REG_EXP_STR`) | Captures standard path segments into `paramMap`. |
| `:label{expr}` | `expr` (custom regex string) | Validates and captures custom regex patterns; enforces non-capturing group constraints. |
Sources: [src/router/reg-exp-router/node.ts:1-3](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L1-L3), [src/router/reg-exp-router/node.ts:69-78](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L69-L78)
> [!CAUTION]
> Inserting conflicting segment types into the same Trie node level—such as mixing literal characters with multi-character wildcards or mixing distinct regular expression patterns—immediately throws `PATH_ERROR`. Custom expressions containing capturing groups without non-capturing prefixes (`(?!:\?)`) are also rejected.
Sources: [src/router/reg-exp-router/node.ts:87-91](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L87-L91), [src/router/reg-exp-router/node.ts:96-102](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L96-L102), [src/router/reg-exp-router/node.ts:117-124](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L117-L124)
## Pattern Compilation and Radix Merging
### Recursive Regex String Synthesis and Child Key Sorting
The `Node` class converts the hierarchical trie structure into a unified regular expression string via the `buildRegExpStr()` method [src/router/reg-exp-router/node.ts:135-161](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L135-L161). Child node keys are retrieved, sorted using the `compareKey` function, and mapped into sub-expressions [src/router/reg-exp-router/node.ts:136-147](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L136-L147).
```typescript
function compareKey(a: string, b: string): number {
if (a.length === 1) {
return b.length === 1 ? (a < b ? -1 : 1) : -1
}
if (b.length === 1) {
return 1
}
// wildcard
if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
return 1
} else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
return -1
}
// label
if (a === LABEL_REG_EXP_STR) {
return 1
} else if (b === LABEL_REG_EXP_STR) {
return -1
}
return a.length === b.length ? (a < b ? -1 : 1) : b.length - a.length
}
```
Sources: [src/router/reg-exp-router/node.ts:20-43](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L20-L43)
The sorting algorithm establishes strict evaluation precedence by organizing node keys in the following order: literal strings, special custom patterns, common label patterns (`[^/]+`), and wildcards (`.*` or `(?:|/.*)`) [src/router/reg-exp-router/node.ts:14-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L14-L19).
```typescript
buildRegExpStr(): string {
const childKeys = Object.keys(this.#children).sort(compareKey)
const strList = childKeys.map((k) => {
const c = this.#children[k]
return (
(typeof c.#varIndex === 'number'
? `(${k})@${c.#varIndex}`
: regExpMetaChars.has(k)
? `\\${k}`
: k) + c.buildRegExpStr()
)
})
if (typeof this.#index === 'number') {
strList.unshift(`#${this.#index}`)
}
if (strList.length === 0) {
return ''
}
if (strList.length === 1) {
return strList[0]
}
return '(?:' + strList.join('|') + ')'
}
```
Sources: [src/router/reg-exp-router/node.ts:135-161](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L135-L161)
> [!NOTE]
> When multiple child nodes exist at the same level, `buildRegExpStr()` joins them with alternation operators (`|`) wrapped in non-capturing groups `(?:...)`. If a node marks a route termination point (`#index`), its handler identifier is prepended to the string list before alternation synthesis [src/router/reg-exp-router/node.ts:149-160](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L149-L160).
Sources: [src/router/reg-exp-router/node.ts:149-160](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L149-L160)
### Wildcard Normalization and Root Compilation
Wildcard routes and trailing patterns undergo specific normalization before and during trie integration [src/router/reg-exp-router/router.ts:20-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L20-L28). The router maintains a `wildcardRegExpCache` to compile wildcard expressions, translating `/*` suffixes into safe literal escape sequences combined with `(?:|/.*)` optional path matchers [src/router/reg-exp-router/router.ts:19-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L19-L28).
```typescript
let wildcardRegExpCache: Record = Object.create(null)
function buildWildcardRegExp(path: string): RegExp {
return (wildcardRegExpCache[path] ??= new RegExp(
path === '*'
? ''
: `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) =>
metaChar ? `\\${metaChar}` : '(?:|/.*)'
)}$`
))
}
```
Sources: [src/router/reg-exp-router/router.ts:19-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L19-L28)
Once the trie graph is fully populated, `Trie.buildRegExp()` finalizes the compiled string by processing handler markers (`#\d+`), parameter markers (`@\d+`), and wildcard endings (`\.\*\$`) [src/router/reg-exp-router/trie.ts:49-73](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L49-L73). It constructs `indexReplacementMap` and `paramReplacementMap` lookup structures to align capturing groups with handler indices, returning a fully operational `RegExp` instance anchored with a caret (`^`) [src/router/reg-exp-router/trie.ts:55-73](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L55-L73).
```typescript
buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] {
let regexp = this.#root.buildRegExpStr()
if (regexp === '') {
return [/^$/, [], []] // never match
}
let captureIndex = 0
const indexReplacementMap: ReplacementMap = []
const paramReplacementMap: ReplacementMap = []
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
if (handlerIndex !== undefined) {
indexReplacementMap[++captureIndex] = Number(handlerIndex)
return '$()'
}
if (paramIndex !== undefined) {
paramReplacementMap[Number(paramIndex)] = ++captureIndex
return ''
}
return ''
})
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap]
}
```
Sources: [src/router/reg-exp-router/trie.ts:49-73](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L49-L73)
## Matcher Execution and Param Extraction
### Single-Pass Regex Matching and Static Map Lookups
When a request path is evaluated, the `match` function first resolves the appropriate `Matcher` tuple for the HTTP method by checking method-specific matchers or falling back to `METHOD_NAME_ALL` [src/router/reg-exp-router/matcher.ts:10-15](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L10-L15).
```typescript
export function match, T>(this: R, method: string, path: string): Result {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const matchers: MatcherMap = (this as any).buildAllMatchers()
const match = ((method, path) => {
const matcher = (matchers[method] || matchers[METHOD_NAME_ALL]) as Matcher
const staticMatch = matcher[2][path]
if (staticMatch) {
return staticMatch
}
```
Sources: [src/router/reg-exp-router/matcher.ts:10-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L10-L20)
Before executing regular expression evaluation, the router checks the `StaticMap` (`matcher[2]`) for an exact path match [src/router/reg-exp-router/matcher.ts:17-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L17-L20). If a static entry exists, it returns the precompiled handler list and empty parameters directly, avoiding regex overhead entirely [src/router/reg-exp-router/matcher.ts:17-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L17-L20). When the path is dynamic, `path.match(matcher[0])` executes a single-pass regular expression match across the compiled routing tree [src/router/reg-exp-router/matcher.ts:22-25](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L22-L25).
```typescript
const match = path.match(matcher[0])
if (!match) {
return [[], emptyParam]
}
const index = match.indexOf('', 1)
return [matcher[1][index], match]
}) as Router['match']
```
Sources: [src/router/reg-exp-router/matcher.ts:21-29](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L21-L29)
> [!NOTE]
> If the regular expression test fails (`!match`), the matcher immediately returns an empty handler list and an empty parameter array `[[], emptyParam]` [src/router/reg-exp-router/matcher.ts:23-25](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L23-L25).
Sources: [src/router/reg-exp-router/matcher.ts:23-25](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L23-L25)
### Index-to-Handler Dispatch and Capture-Group Extraction
Once a successful regex match occurs, the router determines which route branch matched by scanning the match array for the handler index marker [src/router/reg-exp-router/matcher.ts:27-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L27-L28). The expression `match.indexOf('', 1)` finds the empty string boundary or group index corresponding to the active route branch [src/router/reg-exp-router/matcher.ts:27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L27).
```typescript
const index = match.indexOf('', 1)
return [matcher[1][index], match]
```
Sources: [src/router/reg-exp-router/matcher.ts:27-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L27-L28)
The resulting index maps directly to `matcher[1]`, which holds the handler array and pre-mapped parameter keys for that specific route branch [src/router/reg-exp-router/matcher.ts:28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L28). The matched RegExp result array itself is returned alongside the handlers, supplying captured parameter values extracted from dynamic segments [src/router/reg-exp-router/matcher.ts:28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L28).
> [!TIP]
> After the initial match call executes, `this.match` is dynamically rewritten on the router instance to point directly to the inner closure function, bypassing method lookup overhead on all subsequent requests [src/router/reg-exp-router/matcher.ts:14-32](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L14-L32).
Sources: [src/router/reg-exp-router/matcher.ts:14-32](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L14-L32)
## Ahead-of-Time Prepared Matching
### Serialization and Pre-compilation Patterns
To bypass dynamic route compilation overhead during server startup, `PreparedRegExpRouter` enables ahead-of-time initialization [src/router/reg-exp-router/prepared-router.ts:9-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L9-L17). The helper function `buildInitParams` provisions a temporary `RegExpRouter` instance, registers all target paths against `METHOD_NAME_ALL`, and exports the resulting matcher structures [src/router/reg-exp-router/prepared-router.ts:95-154](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L95-L154). It constructs a `relocateMap` that maps individual paths to their corresponding handler indices and parameter index maps [src/router/reg-exp-router/prepared-router.ts:111-144](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L111-L144).
```typescript
export const buildInitParams: (params: {
paths: string[]
}) => ConstructorParameters = ({ paths }) => {
const RegExpRouterWithMatcherExport = class extends RegExpRouter {
buildAndExportAllMatchers() {
return this.buildAllMatchers()
}
}
const router = new RegExpRouterWithMatcherExport()
for (const path of paths) {
router.add(METHOD_NAME_ALL, path, path)
}
const matchers = router.buildAndExportAllMatchers()
const all = matchers[METHOD_NAME_ALL] as Matcher
const relocateMap: RelocateMap = {}
for (const path of paths) {
if (path === '/*' || path === '*') {
continue
}
all[1].forEach((list, i) => {
list.forEach(([p, map]) => {
if (p === path) {
if (relocateMap[path]) {
relocateMap[path][0][1] = {
...relocateMap[path][0][1],
...map,
}
} else {
relocateMap[path] = [[[], map]]
}
if (relocateMap[path][0][0].findIndex((j) => j === i) === -1) {
relocateMap[path][0][0].push(i)
}
}
})
})
for (const path2 in all[2]) {
all[2][path2][0].forEach(([p]) => {
if (p === path) {
relocateMap[path] ||= [[[]]]
const value = path2 === path ? '' : path2
if (relocateMap[path][0][0].findIndex((v) => v === value) === -1) {
relocateMap[path][0][0].push(value)
}
}
})
}
}
for (let i = 0, len = all[1].length; i < len; i++) {
all[1][i] = all[1][i] ? [] : (0 as unknown as HandlerData)
}
for (const path in all[2]) {
all[2][path][0] = []
}
return [matchers, relocateMap]
}
```
Sources: [src/router/reg-exp-router/prepared-router.ts:95-154](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L95-L154)
The companion utility `serializeInitParams` translates these compilation artifacts into stringified JSON formats [src/router/reg-exp-router/prepared-router.ts:156-165](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L156-L165). To preserve native regular expression objects across serialization boundaries, it converts `RegExp` instances into tagged string placeholders (`##...##`) and restores them via regex replacement during output generation [src/router/reg-exp-router/prepared-router.ts:160-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L160-L164).
```typescript
export const serializeInitParams: (
params: ConstructorParameters
) => string = ([matchers, relocateMap]) => {
// Embed the regular expression as a result of `toString()` so that it can be evaluated as JavaScript.
const matchersStr = JSON.stringify(matchers, (_, value) =>
value instanceof RegExp ? `##${value.toString()}##` : value
).replace(/"##(.+?)##"/g, (_, str) => str.replace(/\\\\/g, '\\'))
const relocateMapStr = JSON.stringify(relocateMap)
return `[${matchersStr},${relocateMapStr}]`
}
```
Sources: [src/router/reg-exp-router/prepared-router.ts:156-165](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L156-L165)
### Runtime Mechanics and Relocation Maps
At runtime, `PreparedRegExpRouter` accepts precompiled `MatcherMap` and `RelocateMap` collections directly through its constructor [src/router/reg-exp-router/prepared-router.ts:14-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L14-L17). When additional routes are added dynamically via `add`, the router references the `relocateMap` to insert handlers into pre-allocated matcher slots without rebuilding the trie or re-synthesizing regular expression patterns [src/router/reg-exp-router/prepared-router.ts:47-86](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L47-L86).
```typescript
add(method: string, path: string, handler: T) {
if (!this.#matchers[method]) {
const all = this.#matchers[METHOD_NAME_ALL] as Matcher
const staticMap = {} as StaticMap
for (const key in all[2]) {
staticMap[key] = [all[2][key][0].slice(), emptyParam] as Result
}
this.#matchers[method] = [
all[0],
all[1].map((list) => (Array.isArray(list) ? list.slice() : 0)) as HandlerData[],
staticMap,
]
}
if (path === '/*' || path === '*') {
const handlerData: [T, ParamIndexMap] = [handler, {}]
if (method === METHOD_NAME_ALL) {
for (const m in this.#matchers) {
this.#addWildcard(m, handlerData)
}
} else {
this.#addWildcard(method, handlerData)
}
return
}
const data = this.#relocateMap[path]
if (!data) {
throw new Error(`Path ${path} is not registered`)
}
for (const [indexes, map] of data) {
if (method === METHOD_NAME_ALL) {
for (const m in this.#matchers) {
this.#addPath(m, path, handler, indexes, map)
}
} else {
this.#addPath(method, path, handler, indexes, map)
}
}
}
```
Sources: [src/router/reg-exp-router/prepared-router.ts:47-86](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L47-L86)
> [!WARNING]
> If a route path is registered via `add` that was not included in the initial path array passed to `buildInitParams`, the router throws an error stating that the path is not registered [src/router/reg-exp-router/prepared-router.ts:73-76](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L73-L76).
Sources: [src/router/reg-exp-router/prepared-router.ts:73-76](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L73-L76)
| Parameter / Property | Type | Description |
| :--- | :--- | :--- |
| `#matchers` | `MatcherMap` | Method-indexed collection containing compiled regular expressions, handler lists, and static maps [src/router/reg-exp-router/prepared-router.ts:9-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L9-L17) |
| `#relocateMap` | `RelocateMap` | Mapping of paths to route index arrays and parameter index configurations [src/router/reg-exp-router/prepared-router.ts:7-12](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L7-L12) |
| `buildInitParams` | `Function` | Pre-builds matchers and computes relocation targets from a set of paths [src/router/reg-exp-router/prepared-router.ts:95-97](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L95-L97) |
| `serializeInitParams` | `Function` | Serializes matchers and relocation maps into an evaluable string representation [src/router/reg-exp-router/prepared-router.ts:156-158](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L156-L158) |
Sources: [src/router/reg-exp-router/prepared-router.ts:7-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L7-L17), [src/router/reg-exp-router/prepared-router.ts:95-97](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L95-L97), [src/router/reg-exp-router/prepared-router.ts:156-158](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L156-L158)
## Related
- [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts)
- [Trie and Smart Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/trie-and-smart-routers)
---
## Technical docs: Trie and Smart Routers
URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/trie-and-smart-routers
Relevant source files
The following files were used as context for generating this wiki page:
- [src/router/smart-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts)
- [src/router/trie-router/node.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts)
- [src/router/trie-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/index.ts)
- [src/helper/route/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts)
- [src/router/trie-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts)
- [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts)
- [src/preset/quick.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts)
- [src/router/reg-exp-router/prepared-router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts)
- [src/router/linear-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts)
- [src/router/reg-exp-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts)
- [src/router/reg-exp-router/node.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts)
- [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts)
- [src/hono.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono.ts)
- [src/router/reg-exp-router/trie.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts)
- [src/router/reg-exp-router/matcher.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts)
- [src/middleware/language/language.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts)
- [src/utils/url.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts)
- [src/router/smart-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts)
- [src/helper/dev/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/dev/index.ts)
- [src/router/pattern-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts)
- [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts)
- [src/utils/ipaddr.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts)
- [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json)
- [src/preset/tiny.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts)
- [src/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts)
- [src/router/linear-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/index.ts)
- [src/helper/ssg/utils.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/utils.ts)
- [src/helper/adapter/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts)
- [src/router/reg-exp-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/index.ts)
- [src/router/pattern-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/index.ts)
## Overview
Hono's `TrieRouter` and `SmartRouter` deliver hierarchical prefix routing and dynamic dispatch across multiple matching backends. `TrieRouter` manages route registration through tree node insertion, supporting optional parameter expansion, path segment tokenization, and recursive handler set collection. To combine different routing strategies, `SmartRouter` aggregates multiple router instances, delegating registration to each candidate until a successful match occurs and locking onto the winning backend for subsequent requests. Sources: [src/router/smart-router/router.ts:4-70](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L4-L70), [src/router/trie-router/node.ts:25-112](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L25-L112), [src/router/trie-router/router.ts:5-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts#L5-L27)
## TrieRouter Architecture and Route Registration
### Public Interface and Root Node Management
`TrieRouter` implements the unified `Router` interface, identifying itself via the `name` property set to `'TrieRouter'`. The class initializes a private root `#node` instance of type `Node` inside its constructor to anchor the entire route prefix tree.
```typescript
export class TrieRouter implements Router {
name: string = 'TrieRouter'
#node: Node
constructor() {
this.#node = new Node()
}
...
```
Sources: [src/router/trie-router/router.ts:5-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts#L5-L11)
### Optional Parameter Expansion and Route Insertion
When adding routes through the `add(method, path, handler)` method, `TrieRouter` inspects the incoming route path using `checkOptionalParameter(path)`. If optional parameters are present, the utility returns an array of expanded path variations; the router iterates over these results and inserts each individual variation into the root node. If no optional parameters are detected, the path is inserted directly.
```typescript
add(method: string, path: string, handler: T) {
const results = checkOptionalParameter(path)
if (results) {
for (let i = 0, len = results.length; i < len; i++) {
this.#node.insert(method, results[i], handler)
}
return
}
this.#node.insert(method, path, handler)
}
```
Sources: [src/router/trie-router/router.ts:13-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts#L13-L23)
> [!NOTE]
> `checkOptionalParameter` handles path patterns containing optional segments by generating all possible route combinations, ensuring each variant is separately registered in the prefix tree.
Sources: [src/router/trie-router/router.ts:14-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts#L14-L20)
### Route Matching Delegation
Incoming request matching delegates execution directly to the root node's `search` method, forwarding both the HTTP `method` and request `path` and returning a resolved `Result` structure containing matched handlers and captured parameters.
```typescript
match(method: string, path: string): Result {
return this.#node.search(method, path)
}
```
Sources: [src/router/trie-router/router.ts:25-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts#L25-L27)
## Trie Node Structure and Insertion
### Node Fields and Constructor Initialization
The `Node` class maintains the internal state of the prefix tree using private fields. Each node tracks its registered methods, child nodes, extracted routing patterns, insertion order counters, and parameter records.
```typescript
export class Node {
#methods: Record>[]
#children: Record>
#patterns: Pattern[]
#order: number = 0
#params: Record = emptyParams
constructor(method?: string, handler?: T, children?: Record>) {
this.#children = children || Object.create(null)
this.#methods = []
if (method && handler) {
const m: Record> = Object.create(null)
m[method] = { handler, possibleKeys: [], score: 0 }
this.#methods = [m]
}
this.#patterns = []
}
```
Sources: [src/router/trie-router/node.ts:25-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L25-L42)
> [!NOTE]
> `emptyParams` is initialized via `Object.create(null)` to provide a prototype-free parameter dictionary.
Sources: [src/router/trie-router/node.ts:16-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L16-L16)
### Path Segment Tokenization and Pattern Extraction
During route insertion, `insert(method, path, handler)` increments the node order counter and splits the routing path into individual segments using `splitRoutingPath(path)`. It iterates through each segment, calling `getPattern(p, nextP)` to extract parameter and wildcard patterns.
```typescript
insert(method: string, path: string, handler: T): Node {
this.#order = ++this.#order
// eslint-disable-next-line @typescript-eslint/no-this-alias
let curNode: Node = this
const parts = splitRoutingPath(path)
const possibleKeys: string[] = []
for (let i = 0, len = parts.length; i < len; i++) {
const p: string = parts[i]
const nextP = parts[i + 1]
const pattern = getPattern(p, nextP)
const key = Array.isArray(pattern) ? pattern[0] : p
if (key in curNode.#children) {
curNode = curNode.#children[key]
if (pattern) {
possibleKeys.push(pattern[1])
}
continue
}
```
Sources: [src/router/trie-router/node.ts:44-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L44-L65)
### Recursive Tree Construction and Handler Binding
If a segment key already exists within `curNode.#children`, traversal descends into that child node. Otherwise, a new `Node` instance is instantiated and registered. Extracted patterns are pushed to `#patterns`, and final handler sets are appended to `#methods` with deduplicated `possibleKeys` and an insertion order score.
```typescript
curNode.#children[key] = new Node()
if (pattern) {
curNode.#patterns.push(pattern)
possibleKeys.push(pattern[1])
}
curNode = curNode.#children[key]
}
curNode.#methods.push({
[method]: {
handler,
possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
score: this.#order,
},
})
return curNode
}
```
Sources: [src/router/trie-router/node.ts:66-85](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L66-L85)
> [!WARNING]
> Handler sets filter `possibleKeys` using `a.indexOf(v) === i` to prevent duplicate parameter keys within the same handler registration block.
Sources: [src/router/trie-router/node.ts:76-82](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L76-L82)
## Hierarchical Path Traversal and Matching
### Recursive Search Execution and Queue Management
Path lookup begins by invoking `search(method, path)` on the root node, which splits the request path using `splitPath(path)` and initializes a traversal queue of active nodes (`curNodes`) alongside `curNodesQueue` for handling multi-segment regular expression parameter matches.
```typescript
search(method: string, path: string): [[T, Params][]] {
const handlerSets: HandlerParamsSet[] = []
this.#params = emptyParams
// eslint-disable-next-line @typescript-eslint/no-this-alias
const curNode: Node = this
let curNodes = [curNode]
const parts = splitPath(path)
const curNodesQueue: Node[][] = []
const len = parts.length
let partOffsets: number[] | null = null
```
Sources: [src/router/trie-router/node.ts:114-126](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L114-L126)
### Static Child Lookup and Wildcard Handling
During iteration over path segments, the router checks static child nodes via `node.#children[part]`. When reaching the final path segment on a matching child, it evaluates trailing wildcard children (`nextNode.#children['*']`) and pushes matching handler sets into the accumulation array.
```typescript
for (let i = 0; i < len; i++) {
const part: string = parts[i]
const isLast = i === len - 1
const tempNodes: Node[] = []
for (let j = 0, len2 = curNodes.length; j < len2; j++) {
const node = curNodes[j]
const nextNode = node.#children[part]
if (nextNode) {
nextNode.#params = node.#params
if (isLast) {
// '/hello/*' => match '/hello'
if (nextNode.#children['*']) {
this.#pushHandlerSets(handlerSets, nextNode.#children['*'], method, node.#params)
}
this.#pushHandlerSets(handlerSets, nextNode, method, node.#params)
} else {
tempNodes.push(nextNode)
}
}
```
Sources: [src/router/trie-router/node.ts:127-148](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L127-L148)
> [!NOTE]
> Wildcard patterns (`*`) directly inspect child nodes keyed by `*`, pushing their associated handler sets and enqueuing the wildcard astNode for subsequent path segments.
Sources: [src/router/trie-router/node.ts:153-163](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L153-L163)
### Parameter Capture and Regular Expression Matchers
Nodes with patterns evaluate parameters and regular expressions against the remaining path string using precomputed part offsets. If a regular expression matcher succeeds, captured values populate the parameters dictionary and child nodes are scheduled via `curNodesQueue`.
```typescript
const [key, name, matcher] = pattern
if (!part && !(matcher instanceof RegExp)) {
continue
}
const child = node.#children[key]
// `/js/:filename{[a-z]+.js}` => match /js/chunk/123.js
if (matcher instanceof RegExp) {
if (partOffsets === null) {
partOffsets = new Array(len)
let offset = path[0] === '/' ? 1 : 0
for (let p = 0; p < len; p++) {
partOffsets[p] = offset
offset += parts[p].length + 1
}
}
const restPathString = path.substring(partOffsets[i])
const m = matcher.exec(restPathString)
if (m) {
params[name] = m[0]
this.#pushHandlerSets(handlerSets, child, method, node.#params, params)
if (hasChildren(child.#children)) {
child.#params = params
const componentCount = m[0].match(/\//)?.length ?? 0
const targetCurNodes = (curNodesQueue[componentCount] ||= [])
targetCurNodes.push(child)
}
continue
}
}
if (matcher === true || matcher.test(part)) {
params[name] = part
if (isLast) {
```
Sources: [src/router/trie-router/node.ts:165-203](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L165-L203)
### Handler Set Collection
The `#pushHandlerSets` helper method resolves method-specific handlers or `METHOD_NAME_ALL` fallbacks, binds parameter dictionaries from `possibleKeys`, and populates the output `handlerSets` collection.
```typescript
#pushHandlerSets(
handlerSets: HandlerParamsSet[],
node: Node,
method: string,
nodeParams: Record,
params?: Record
): void {
for (let i = 0, len = node.#methods.length; i < len; i++) {
const m = node.#methods[i]
const handlerSet = (m[method] || m[METHOD_NAME_ALL]) as HandlerParamsSet
const processedSet: Record = {}
if (handlerSet !== undefined) {
handlerSet.params = Object.create(null)
handlerSets.push(handlerSet)
if (nodeParams !== emptyParams || (params && params !== emptyParams)) {
for (let i = 0, len = handlerSet.possibleKeys.length; i < len; i++) {
const key = handlerSet.possibleKeys[i]
const processed = processedSet[handlerSet.score]
handlerSet.params[key] =
params?.[key] && !processed ? params[key] : (nodeParams[key] ?? params?.[key])
processedSet[handlerSet.score] = true
}
}
}
}
}
```
Sources: [src/router/trie-router/node.ts:87-112](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L87-L112)
> [!WARNING]
> Parameter inheritance checks `nodeParams` against `params` using `processedSet` deduplication flags to ensure route parameters maintain correct scope across hierarchical child transitions.
Sources: [src/router/trie-router/node.ts:97-110](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L97-L110)
## SmartRouter Architecture and Routing Backends
### Multi-Router Aggregation and Registration Contract
The `SmartRouter` class implements the unified `Router` interface by aggregating an array of candidate router backends via its constructor initialization parameter (`init.routers`). During the registration phase, calling `add(method, path, handler)` pushes route tuples `[method, path, handler]` into the internal `#routes` collection. If route addition is attempted after the matcher has already been built, it throws an error with the message defined by `MESSAGE_MATCHER_IS_ALREADY_BUILT`.
```typescript
export class SmartRouter implements Router {
name: string = 'SmartRouter'
#routers: Router[] = []
#routes?: [string, string, T][] = []
constructor(init: { routers: Router[] }) {
this.#routers = init.routers
}
add(method: string, path: string, handler: T) {
if (!this.#routes) {
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT)
}
this.#routes.push([method, path, handler])
}
```
Sources: [src/router/smart-router/router.ts:4-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L4-L20)
> [!WARNING]
> Calling `add()` after matching has been evaluated throws an error because `#routes` is set to `undefined` once an active router locks in.
Sources: [src/router/smart-router/router.ts:13-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L13-L19), [src/router/smart-router/router.ts:48-48](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L48-L48)
### Routing Delegation and Matcher Locking
When `match(method, path)` is invoked, `SmartRouter` iterates through the candidate routers in `#routers`, populating each candidate with all accumulated routes from `#routes` and testing them sequentially. If an `UnsupportedPathError` occurs on a candidate router, the loop catches the exception, ignores it with `continue`, and falls back to the next available router backend.
```typescript
match(method: string, path: string): Result {
if (!this.#routes) {
throw new Error('Fatal error')
}
const routers = this.#routers
const routes = this.#routes
const len = routers.length
let i = 0
let res
for (; i < len; i++) {
const router = routers[i]
try {
for (let i = 0, len = routes.length; i < len; i++) {
router.add(...routes[i])
}
res = router.match(method, path)
} catch (e) {
if (e instanceof UnsupportedPathError) {
continue
}
throw e
}
this.match = router.match.bind(router)
this.#routers = [router]
this.#routes = undefined
break
}
```
Sources: [src/router/smart-router/router.ts:21-51](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L21-L51)
> [!TIP]
> Upon a successful match, `SmartRouter` mutates its own prototype methods and state by binding `this.match` directly to the winning `router.match`, reducing `#routers` to a single-element array containing the active router, and clearing `#routes`.
Sources: [src/router/smart-router/router.ts:46-49](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L46-L49)
### Router State Properties
| Property / Method | Type / Signature | Description |
| :--- | :--- | :--- |
| `name` | `string` | Identifies the router name, initialized as `'SmartRouter'` and updated to include the active router name post-selection (e.g. `SmartRouter + RegExpRouter`). |
| `#routers` | `Router[]` | Internal array of candidate routing backends provided at instantiation, narrowing down to the single active router upon successful execution. |
| `#routes` | `[string, string, T][] \| undefined` | Temporary storage holding registered route tuples before matcher locking; set to `undefined` once a router successfully handles a match. |
| `activeRouter` | `Router` | Getter returning the single active router instance once routing has locked in, throwing an error if routes are still pending or multiple routers remain. |
```typescript
export class SmartRouter implements Router {
name: string = 'SmartRouter'
#routers: Router[] = []
#routes?: [string, string, T][] = []
constructor(init: { routers: Router[] }) {
this.#routers = init.routers
}
```
Sources: [src/router/smart-router/router.ts:4-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L4-L11), [src/router/smart-router/router.ts:63-69](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L63-L69)
## Dynamic Router Selection and Fallback
### Heuristic Selection on First Match
`SmartRouter` resolves which underlying router backend handles incoming traffic dynamically during the initial call to `match(method, path)`. It iterates through each candidate router in `#routers`, replaying all buffered route tuples from `#routes` into the candidate via its `add()` method, and immediately attempts to match the target request. If a candidate router successfully executes the match without throwing an `UnsupportedPathError` or other exceptions, selection halts immediately via a `break` statement.
```typescript
const routers = this.#routers
const routes = this.#routes
const len = routers.length
let i = 0
let res
for (; i < len; i++) {
const router = routers[i]
try {
for (let i = 0, len = routes.length; i < len; i++) {
router.add(...routes[i])
}
res = router.match(method, path)
} catch (e) {
if (e instanceof UnsupportedPathError) {
continue
}
throw e
}
this.match = router.match.bind(router)
this.#routers = [router]
this.#routes = undefined
break
}
```
Sources: [src/router/smart-router/router.ts:26-50](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L26-L50)
> [!WARNING]
> If all candidate routers fail to match or throw unhandled exceptions, the outer loop completes without breaking (`i === len`), triggering a fatal error throw that halts execution.
Sources: [src/router/smart-router/router.ts:52-55](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L52-L55)
### UnsupportedPathError Handling and Matcher Locking
During heuristic evaluation, candidate routers may encounter path syntax or expression structures they cannot process, throwing an `UnsupportedPathError`. The `try...catch` block inspects caught errors; if `e instanceof UnsupportedPathError` is true, the error is suppressed, and execution continues to the next candidate router in the sequence. Any other error type is rethrown immediately.
```typescript
try {
for (let i = 0, len = routes.length; i < len; i++) {
router.add(...routes[i])
}
res = router.match(method, path)
} catch (e) {
if (e instanceof UnsupportedPathError) {
continue
}
throw e
}
```
Sources: [src/router/smart-router/router.ts:34-44](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L34-L44)
> [!TIP]
> Once a candidate successfully matches, `SmartRouter` locks its matcher by reassigning `this.match` to bind directly to the winning `router.match`, collapsing `#routers` to a single-element array containing only the active router, setting `#routes` to `undefined`, and updating `this.name` to reflect the active backend (e.g., `SmartRouter + RegExpRouter`). Subsequent requests bypass heuristic iteration entirely.
Sources: [src/router/smart-router/router.ts:46-58](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L46-L58)
## Related
- [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts)
- [RegExp Router](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/regexp-router)
---
## Technical docs: Linear and Pattern Routers
URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/linear-and-pattern-routers
Relevant source files
The following files were used as context for generating this wiki page:
- [src/router/linear-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts)
- [src/router/pattern-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts)
- [src/router/reg-exp-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts)
- [src/router/reg-exp-router/prepared-router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts)
- [src/helper/route/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts)
- [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts)
- [src/router/pattern-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/index.ts)
- [src/router/reg-exp-router/matcher.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts)
- [src/utils/url.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts)
- [src/preset/tiny.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts)
- [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts)
- [src/router/linear-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/index.ts)
- [src/preset/quick.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts)
- [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts)
- [src/router/trie-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts)
- [src/router/trie-router/node.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts)
- [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts)
- [src/router/smart-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts)
- [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json)
- [src/router/reg-exp-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/index.ts)
- [src/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts)
- [src/router/reg-exp-router/node.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts)
- [src/router/reg-exp-router/trie.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts)
- [src/router/trie-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/index.ts)
- [src/router/smart-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts)
## Overview
Linear and Pattern routers provide lightweight path-matching backends designed to minimize bundle footprints and execution overhead in constrained environments. Operating as alternative routing engines alongside [Trie and Smart Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/trie-and-smart-routers) and [RegExp Router](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/regexp-router), these implementations satisfy the unified [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts) interface while trading complex trie structures and regex compilation for straightforward linear scanning or direct pattern compilation. By storing routes in linear arrays or evaluating dynamic path segments via native regular expressions, they power compact distribution builds such as `[[Presets and Builds]]` while seamlessly integrating with the core routing lifecycle.
Sources: [src/router/linear-router/router.ts:11-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L11-L23), [src/router/pattern-router/router.ts:8-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L8-L42), [src/router.ts:29-52](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L29-L52)
## Minimalist Router Architecture and Tradeoffs
### Architectural Roles
`LinearRouter` and `PatternRouter` implement the unified `Router` interface through straightforward, dependency-free mechanisms designed for minimal code size and memory overhead. `LinearRouter` stores registered routes inside a private array (`#routes: [string, string, T][]`), processing them sequentially during route matching without compiling regular expressions at definition time. Conversely, `PatternRouter` compiles path definitions directly into native `RegExp` instances upon registration, storing them alongside methods in its `#routes` array.
Sources: [src/router/linear-router/router.ts:11-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L11-L23), [src/router/pattern-router/router.ts:8-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L8-L42)
### Design Tradeoffs and Limitations
Both routers balance implementation simplicity against runtime performance characteristics. Because `LinearRouter` evaluates path segments and substring positions via string index checks (`indexOf`) and custom iteration loops, it avoids regex compilation overhead during initialization but incurs linear scan costs ($O(N)$) proportional to the registered route count during request matching.
`PatternRouter` delegates matching directly to the JavaScript engine's regex execution engine using named capture groups (`match.groups`), but both routers enforce strict structural boundaries on path syntax. When confronted with unsupported path combinations—such as combining labels and wildcards within the same route path—both implementations throw an `UnsupportedPathError`.
Sources: [src/router/linear-router/router.ts:25-143](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L25-L143), [src/router/pattern-router/router.ts:44-59](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L44-L59)
> [!WARNING]
> Combining wildcard characters (`*`) and labeled parameters (`:name`) within a single route path triggers an `UnsupportedPathError` in both `LinearRouter` and `PatternRouter`.
Sources: [src/router/linear-router/router.ts:136-138](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L136-L138), [src/router/pattern-router/router.ts:33-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L33-L41)
## Linear Route Registration and Execution
### Internal Storage and Route Registration
`LinearRouter` implements the `Router` interface by maintaining a private tuple array `#routes: [string, string, T][]` that stores the HTTP method, route pattern, and handler for every registered endpoint. When `add(method, path, handler)` is invoked, the router checks the incoming path for optional parameter syntax via `checkOptionalParameter(path)`. If optional parameters expand the path definition into multiple variations, each resulting path is appended as a distinct tuple entry into `#routes`.
```typescript
export class LinearRouter implements Router {
name: string = 'LinearRouter'
#routes: [string, string, T][] = []
add(method: string, path: string, handler: T) {
for (
let i = 0, paths = checkOptionalParameter(path) || [path], len = paths.length;
i < len;
i++
) {
this.#routes.push([method, paths[i], handler])
}
}
```
Sources: [src/router/linear-router/router.ts:11-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L11-L23)
### Sequential Scanning and Matching Branches
During `match(method, path)`, `LinearRouter` iterates through `#routes` using a labeled loop (`ROUTES_LOOP`) to evaluate every registered route sequentially. Each candidate tuple's method is tested for an exact match against the incoming request method or the catch-all constant `METHOD_NAME_ALL`. If the method matches, the evaluation branches based on the structural characteristics of the `routePath` string: static paths, trailing or embedded wildcards, labeled parameters, or combined wildcards and labels.
```typescript
match(method: string, path: string): Result {
const handlers: [T, Params][] = []
ROUTES_LOOP: for (let i = 0, len = this.#routes.length; i < len; i++) {
const [routeMethod, routePath, handler] = this.#routes[i]
if (routeMethod === method || routeMethod === METHOD_NAME_ALL) {
if (routePath === '*' || routePath === '/*') {
handlers.push([handler, emptyParams])
continue
}
const hasStar = routePath.indexOf('*') !== -1
const hasLabel = routePath.indexOf(':') !== -1
if (!hasStar && !hasLabel) {
if (routePath === path || routePath + '/' === path) {
handlers.push([handler, emptyParams])
}
```
Sources: [src/router/linear-router/router.ts:25-40](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L25-L40)
| Route Type Condition | Path Structure Indicators | Parameter Extraction Mechanism |
| :--- | :--- | :--- |
| Static Route | `!hasStar && !hasLabel` | `emptyParams` (no parameters) |
| Wildcard Route | `hasStar && !hasLabel` | `emptyParams` via substring and slash checks |
| Labeled Parameter Route | `hasLabel && !hasStar` | `Record` via `splitPathRe` and regex indices |
| Unsupported Combination | `hasLabel && hasStar` | Throws `UnsupportedPathError` |
```typescript
const hasStar = routePath.indexOf('*') !== -1
const hasLabel = routePath.indexOf(':') !== -1
if (!hasStar && !hasLabel) {
if (routePath === path || routePath + '/' === path) {
handlers.push([handler, emptyParams])
}
} else if (hasStar && !hasLabel) {
const endsWithStar = routePath.charCodeAt(routePath.length - 1) === 42
const parts = (endsWithStar ? routePath.slice(0, -2) : routePath).split(splitByStarRe)
const lastIndex = parts.length - 1
for (let j = 0, pos = 0, len = parts.length; j < len; j++) {
const part = parts[j]
const index = path.indexOf(part, pos)
if (index !== pos) {
continue ROUTES_LOOP
}
pos += part.length
if (j === lastIndex) {
if (
!endsWithStar &&
pos !== path.length &&
!(pos === path.length - 1 && path.charCodeAt(pos) === 47)
) {
continue ROUTES_LOOP
}
} else {
const index = path.indexOf('/', pos)
if (index === -1) {
continue ROUTES_LOOP
}
pos = index
}
}
handlers.push([handler, emptyParams])
} else if (hasLabel && !hasStar) {
const params: Record = Object.create(null)
const parts = routePath.match(splitPathRe) as string[]
const lastIndex = parts.length - 1
for (let j = 0, pos = 0, len = parts.length; j < len; j++) {
if (pos === -1 || pos >= path.length) {
continue ROUTES_LOOP
}
const part = parts[j]
if (part.charCodeAt(1) === 58) {
if (path.charCodeAt(pos) !== 47) {
continue ROUTES_LOOP
}
// /:label
let name = part.slice(2)
let value
if (name.charCodeAt(name.length - 1) === 125) {
// :label{pattern}
const openBracePos = name.indexOf('{')
const next = parts[j + 1]
const lookahead = next && next[1] !== ':' && next[1] !== '*' ? `(?=${next})` : ''
const pattern = name.slice(openBracePos + 1, -1) + lookahead
const restPath = path.slice(pos + 1)
const match = new RegExp(pattern, 'd').exec(restPath) as RegExpMatchArrayWithIndices
if (!match || match.indices[0][0] !== 0 || match.indices[0][1] === 0) {
continue ROUTES_LOOP
}
name = name.slice(0, openBracePos)
value = restPath.slice(...match.indices[0])
pos += match.indices[0][1] + 1
} else {
let endValuePos = path.indexOf('/', pos + 1)
if (endValuePos === -1) {
if (pos + 1 === path.length) {
continue ROUTES_LOOP
}
endValuePos = path.length
}
value = path.slice(pos + 1, endValuePos)
pos = endValuePos
}
```
Sources: [src/router/linear-router/router.ts:35-138](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L35-L138)
> [!NOTE]
> `LinearRouter` does not halt execution upon finding the first matching route; it continues scanning the entire `#routes` array and collects all matching handlers into a results array.
Sources: [src/router/linear-router/router.ts:25-143](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L25-L143)
## Pattern Matching and Dynamic Evaluation
### Path Pattern Compilation and Segment Parsing
`PatternRouter` registers routes by parsing path strings into compiled regular expressions stored in `#routes: Route[]`, where each tuple contains `[RegExp, string, T]` representing the compiled pattern, HTTP method, and handler. When `add(method, path, handler)` runs, it checks whether `path` ends with an asterisk and strips `/*` if present. If `path` ends with a question mark, it strips the `?` and recursively invokes `this.add` on the path with the final segment removed via `path.replace(/\/[^/]+$/, '')`.
```typescript
add(method: string, path: string, handler: T) {
const endsWithWildcard = path.at(-1) === '*'
if (endsWithWildcard) {
path = path.slice(0, -2)
}
if (path.at(-1) === '?') {
path = path.slice(0, -1)
this.add(method, path.replace(/\/[^/]+$/, ''), handler)
}
```
Sources: [src/router/pattern-router/router.ts:12-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L12-L20)
The router splits and transforms the path into regex tokens using `path.match(/\/?(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/?[^\/\?]+/g)`. Each matched segment is mapped: labeled parameters matching `^\/:([^{]+)(?:{(.*)})?` compile into named capture groups `/(?<${match[1]}>${match[2] || '[^/]+'})`, wildcard segments (`/*`) translate to `/[^/]+`, and static segments escape special characters using `/[.\\+*[^\]$()]/g`. The resulting parts are joined between `^` and `/?$` (or `$/` if ending with a wildcard) to instantiate the `RegExp` object.
```typescript
const parts = (path.match(/\/?(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/?[^\/\?]+/g) || []).map(
(part) => {
const match = part.match(/^\/:([^{]+)(?:{(.*)})?/)
return match
? `/(?<${match[1]}>${match[2] || '[^/]+'})`
: part === '/*'
? '/[^/]+'
: part.replace(/[.\\+*[^\]$()]/g, '\\$&')
}
)
try {
this.#routes.push([
new RegExp(`^${parts.join('')}${endsWithWildcard ? '' : '/?$'}`),
method,
handler,
])
```
Sources: [src/router/pattern-router/router.ts:21-38](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L21-L38)
> [!TIP]
> Custom regex constraints inside route parameters—such as numeric bounds or character classes defined in curly braces—are preserved directly during segment extraction and compiled into the named capture group expression.
Sources: [src/router/pattern-router/router.ts:24-26](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L24-L26)
### Request Match Execution and Parameter Extraction
During `match(method, path)`, `PatternRouter` initializes an empty `handlers: [T, Params][]` array and loops through every entry in `#routes`. It tests each route method against the incoming `method` or `METHOD_NAME_ALL`. When the method matches, it executes the compiled regex pattern against the request `path`. If `pattern.exec(path)` succeeds, it pushes the handler and extracted `match.groups` (falling back to `emptyParams` created via `Object.create(null)`) into the handlers array, returning `[handlers]` upon completion.
```typescript
match(method: string, path: string): Result {
const handlers: [T, Params][] = []
for (let i = 0, len = this.#routes.length; i < len; i++) {
const [pattern, routeMethod, handler] = this.#routes[i]
if (routeMethod === method || routeMethod === METHOD_NAME_ALL) {
const match = pattern.exec(path)
if (match) {
handlers.push([handler, match.groups || emptyParams])
}
}
}
return [handlers]
}
```
Sources: [src/router/pattern-router/router.ts:44-59](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L44-L59)
## Path Support and Fallback Errors
### Handling of Unsupported Syntax and Optional Parameters
Both `LinearRouter` and `PatternRouter` enforce specific path composition rules and handle optional trailing parameters during route registration. In `LinearRouter`, the `add` method uses `checkOptionalParameter(path)` from shared URL utilities to expand optional path variations before pushing them into the `#routes` array.
```typescript
add(method: string, path: string, handler: T) {
for (
let i = 0, paths = checkOptionalParameter(path) || [path], len = paths.length;
i < len;
i++
) {
this.#routes.push([method, paths[i], handler])
}
}
```
Sources: [src/router/linear-router/router.ts:15-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L15-L23)
In `PatternRouter`, optional parameters ending with a question mark (`?`) are processed during registration by stripping the trailing `?` character and recursively invoking `this.add` with the preceding path segment removed via `path.replace(/\/[^/]+$/, '')`.
```typescript
if (path.at(-1) === '?') {
path = path.slice(0, -1)
this.add(method, path.replace(/\/[^/]+$/, ''), handler)
}
```
Sources: [src/router/pattern-router/router.ts:17-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L17-L20)
> [!WARNING]
> Combining labeled parameters and wildcards within the same route path in `LinearRouter` (`hasLabel && hasStar`) is unsupported and explicitly triggers an error.
Sources: [src/router/linear-router/router.ts:136-138](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L136-L138)
### Throwing of UnsupportedPathError
When path compilation or syntax evaluation encounters malformed expressions or unsupported combinations, both routers throw an `UnsupportedPathError` imported from the core router module. In `LinearRouter`, this occurs synchronously inside `match` when both label and star flags evaluate to true on a route path.
```typescript
} else if (hasLabel && hasStar) {
throw new UnsupportedPathError()
}
```
Sources: [src/router/linear-router/router.ts:136-138](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L136-L138)
In `PatternRouter`, route compilation is wrapped in a `try...catch` block. If instantiating the dynamic `RegExp` object fails due to invalid regular expression syntax or unsupported token combinations in path segments, the catch block intercepts the error and throws an `UnsupportedPathError`.
```typescript
try {
this.#routes.push([
new RegExp(`^${parts.join('')}${endsWithWildcard ? '' : '/?$'}`),
method,
handler,
])
} catch {
throw new UnsupportedPathError()
}
```
Sources: [src/router/pattern-router/router.ts:33-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L33-L41)
| Router Implementation | Error Trigger Location | Failure Condition | Thrown Exception |
| :--- | :--- | :--- | :--- |
| `LinearRouter` | `match()` method | Route path contains both label (`:`) and wildcard (`*`) | `UnsupportedPathError` |
| `PatternRouter` | `add()` method | `new RegExp()` constructor throws on malformed syntax | `UnsupportedPathError` |
```typescript
} else if (hasLabel && hasStar) {
throw new UnsupportedPathError()
}
…
try {
this.#routes.push([
new RegExp(`^${parts.join('')}${endsWithWildcard ? '' : '/?$'}`),
method,
handler,
])
} catch {
throw new UnsupportedPathError()
}
```
Sources: [src/router/linear-router/router.ts:136-138](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L136-L138), [src/router/pattern-router/router.ts:33-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L33-L41)
## Preset Integration and Size Optimization
### Distribution Entry Points and Preset Routing
Hono configures package export maps in `package.json` to expose specialized distribution bundles and entry points, including lightweight presets like `tiny` and `quick`, alongside individual router modules such as `[[LinearRouter]]` and `[[PatternRouter]]`.
```json
"./router/linear-router": {
"types": "./dist/types/router/linear-router/index.d.ts",
"import": "./dist/router/linear-router/index.js",
"require": "./dist/cjs/router/linear-router/index.js"
},
```
Sources: [package.json:308-312](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L308-L312)
| Export Target Key | Types Definition Path | Import / ESM Path | Require / CJS Path |
| :--- | :--- | :--- | :--- |
| `./router/linear-router` | `./dist/types/router/linear-router/index.d.ts` | `./dist/router/linear-router/index.js` | `./dist/cjs/router/linear-router/index.js` |
| `./router/pattern-router` | `./dist/types/router/pattern-router/index.d.ts` | `./dist/router/pattern-router/index.js` | `./dist/cjs/router/pattern-router/index.js` |
| `./router/trie-router` | `./dist/types/router/trie-router/index.d.ts` | `./dist/router/trie-router/index.js` | `./dist/cjs/router/trie-router/index.js` |
| `./router/reg-exp-router` | `./dist/types/router/reg-exp-router/index.d.ts` | `./dist/router/reg-exp-router/index.js` | `./dist/cjs/router/reg-exp-router/index.js` |
| `./router/smart-router` | `./dist/types/router/smart-router/index.d.ts` | `./dist/router/smart-router/index.js` | `./dist/cjs/router/smart-router/index.js` |
```json
"./router/reg-exp-router": {
"types": "./dist/types/router/reg-exp-router/index.d.ts",
"import": "./dist/router/reg-exp-router/index.js",
"require": "./dist/cjs/router/reg-exp-router/index.js"
},
"./router/smart-router": {
"types": "./dist/types/router/smart-router/index.d.ts",
"import": "./dist/router/smart-router/index.js",
"require": "./dist/cjs/router/smart-router/index.js"
},
"./router/trie-router": {
"types": "./dist/types/router/trie-router/index.d.ts",
"import": "./dist/router/trie-router/index.js",
"require": "./dist/cjs/router/trie-router/index.js"
},
"./router/pattern-router": {
"types": "./dist/types/router/pattern-router/index.d.ts",
"import": "./dist/router/pattern-router/index.js",
"require": "./dist/cjs/router/pattern-router/index.js"
},
"./router/linear-router": {
"types": "./dist/types/router/linear-router/index.d.ts",
"import": "./dist/router/linear-router/index.js",
"require": "./dist/cjs/router/linear-router/index.js"
},
```
Sources: [package.json:288-312](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L288-L312)
### Type Version Mappings
Type definitions for lightweight bundle targets and router exports are mapped explicitly within the `typesVersions` configuration block of `package.json`, ensuring correct TypeScript resolution in size-constrained environments [Presets and Builds](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/presets-and-builds).
```json
"tiny": [
"./dist/types/preset/tiny"
],
"quick": [
"./dist/types/preset/quick"
],
```
Sources: [package.json:425-430](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L425-L430)
## Related
- [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts)
- [Presets and Builds](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/presets-and-builds)
---
## Technical docs: Runtime Adapters
URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/runtime-adapters/runtime-adapters
Relevant source files
The following files were used as context for generating this wiki page:
- [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts)
- [src/adapter/cloudflare-pages/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/index.ts)
- [src/helper/adapter/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts)
- [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts)
- [src/adapter/cloudflare-workers/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/index.ts)
- [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts)
- [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts)
- [runtime-tests/workerd/index.ts](https://github.com/blade47/workerd/index.ts)
- [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json)
- [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts)
- [src/adapter/service-worker/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/index.ts)
- [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts)
- [src/adapter/cloudflare-workers/serve-static-module.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/serve-static-module.ts)
- [src/adapter/cloudflare-pages/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/conninfo.ts)
- [src/adapter/cloudflare-workers/serve-static.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/serve-static.ts)
- [src/adapter/netlify/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/index.ts)
- [src/adapter/cloudflare-workers/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/websocket.ts)
- [src/middleware/jsx-renderer/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts)
- [src/adapter/vercel/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/index.ts)
- [src/adapter/bun/serve-static.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/serve-static.ts)
- [src/adapter/service-worker/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/handler.ts)
- [src/adapter/bun/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/index.ts)
- [src/adapter/lambda-edge/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/index.ts)
- [src/adapter/deno/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/index.ts)
- [src/adapter/vercel/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/handler.ts)
- [src/middleware/serve-static/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/serve-static/index.ts)
- [src/middleware/context-storage/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts)
- [src/adapter/netlify/mod.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/mod.ts)
- [src/adapter/cloudflare-workers/utils.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/utils.ts)
- [src/adapter/cloudflare-workers/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/conninfo.ts)
## Overview
Runtime Adapters bridge Hono's Web Standard-based [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core) and [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) with platform-specific execution environments, request event structures, bindings, and asset-serving facilities. Different serverless, edge, and worker runtimes utilize disparate native entry points, event signatures, and connection metadata mechanisms that diverge from standard `fetch` event flows. Hono's adapter subsystems translate these proprietary structures into clean Web Standard `Request` and `Response` objects, expose secure connection info, and integrate environment bindings seamlessly.
Sources: [src/adapter/cloudflare-pages/handler.ts:32-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L32-L46)
---
## AWS Lambda Adapters
The AWS Lambda-Edge adapter processes CloudFront edge events (`CloudFrontEdgeEvent`) by mapping incoming CloudFront request structures into a Web Standard `Request` object. When an incoming request carries a query string, host header, or body data (including base64-encoded payloads via `decodeBase64`), `createRequest` reconstructs a full URL and populates request headers.
Sources: [src/adapter/lambda-edge/handler.ts:116-138](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts#L116-L138), [src/adapter/lambda-edge/handler.ts:152-184](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts#L152-L184)
The execution flow transforms responses back into CloudFront-compatible formats through `createResult`. If the response content type indicates binary data according to `isContentTypeBinary`, the body is encoded using `encodeBase64` from array buffers, setting `bodyEncoding: 'base64'`.
```typescript
export const isContentTypeBinary = (contentType: string): boolean => {
return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test(
contentType
)
}
```
Sources: [src/adapter/lambda-edge/handler.ts:140-150](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts#L140-L150), [src/adapter/lambda-edge/handler.ts:202-206](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts#L202-L206)
---
## Cloudflare Adapters
Cloudflare runtime adapters support both Cloudflare Workers (`workerd`) and Cloudflare Pages. The Cloudflare Workers adapter exposes module-based static asset handling via `getContentFromKVAsset`, WebSocket upgrading through `upgradeWebSocket`, and remote IP retrieval via `getConnInfo`. Static asset request flows are executed through the call chain `module` (in `serve-static-module.ts`) delegating to `serveStatic` (in `serve-static.ts`), which in turn invokes the base `serveStatic` middleware to resolve MIME types and decode URIs.
```mermaid
sequenceDiagram
participant Mod as module()
participant CFSS as serveStatic()
participant BaseSS as baseServeStatic()
Mod->>CFSS: serveStatic(options)
CFSS->>BaseSS: baseServeStatic(options with getContent)
BaseSS-->>CFSS: Response / Content
CFSS-->>Mod: MiddlewareHandler Response
```
Sources: [src/adapter/cloudflare-workers/serve-static-module.ts:6-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/serve-static-module.ts#L6-L10), [src/adapter/cloudflare-workers/serve-static.ts:21-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/serve-static.ts#L21-L42), [src/middleware/serve-static/index.ts:35-126](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/serve-static/index.ts#L35-L126)
Cloudflare Pages adapters provide `handle` for routing Pages Functions and `handleMiddleware` for executing individual middleware layers against `EventContext`. The `serveStatic` helper inside Cloudflare Pages queries `env.ASSETS.fetch` directly to serve assets from advanced mode configurations.
```typescript
export const serveStatic = (): MiddlewareHandler => {
return async (c) => {
const env = c.env as { ASSETS: FetcherLike }
const res = await env.ASSETS.fetch(c.req.raw)
if (res.status === 404) {
return c.notFound()
}
return res
}
}
```
Sources: [src/adapter/cloudflare-pages/handler.ts:32-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L32-L46), [src/adapter/cloudflare-pages/handler.ts:114-123](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L114-L123)
---
## Edge and Serverless Adapters
Edge and serverless adapters unify other hosting providers like Vercel, Netlify, and generic Service Workers. The Vercel adapter exports a minimal request handler that forwards incoming requests directly to `app.fetch(req)`.
Sources: [src/adapter/vercel/handler.ts:4-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/handler.ts#L4-L8), [src/adapter/netlify/handler.ts:4-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts#L4-L10)
Similarly, the Netlify adapter wraps requests into Hono execution calls with binding contexts. Service worker handlers listen for fetch events (`addEventListener('fetch')`), invoking `app.fetch` with execution contexts and falling back to global fetch operations on 404 statuses if configured.
```typescript
export const handle = (
app: Hono,
opts: HandleOptions = {
fetch: globalThis.fetch.bind(globalThis),
}
): Handler => {
return (evt) => {
evt.respondWith(
(async () => {
const res = await app.fetch(evt.request, {}, evt)
if (opts.fetch && res.status === 404) {
return await opts.fetch(evt.request)
}
return res
})()
)
}
}
```
Sources: [src/adapter/service-worker/handler.ts:18-36](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/handler.ts#L18-L36), [src/adapter/service-worker/index.ts:28-34](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/index.ts#L28-L34)
---
## Runtime Detection and Environment Helper
The adapter helper module provides runtime detection and environment binding resolution via `getRuntimeKey()` and `env(c)`. `getRuntimeKey()` inspects `navigator.userAgent`, global objects (`EdgeRuntime`, `fastly`), and `process.release.name` to categorize the host engine into a recognized `Runtime` type.
| Runtime Key | Detection Condition | Environment Source |
| :--- | :--- | :--- |
| `deno` | `navigator.userAgent` starts with `'Deno'` | `Deno.env.toObject()` |
| `bun` | `navigator.userAgent` starts with `'Bun'` | `globalEnv` (`process.env`) |
| `workerd` | `navigator.userAgent` starts with `'Cloudflare-Workers'` | `c.env` |
| `node` | `global.process.release.name === 'node'` | `globalEnv` (`process.env`) |
| `edge-light` | `typeof global.EdgeRuntime === 'string'` | `globalEnv` (`process.env`) |
| `fastly` | `global.fastly !== undefined` | `{}` |
| `other` | Fallback when undetected | `{}` |
Sources: [src/helper/adapter/index.ts:8-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L8-L41), [src/helper/adapter/index.ts:43-84](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L43-L84)
## Related
- [Static File Serving](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-file-serving)
- [Request Lifecycle](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/request-lifecycle)
---
## Technical docs: Bun Adapter
URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/runtime-adapters/bun-adapter
Relevant source files
The following files were used as context for generating this wiki page:
- [src/adapter/bun/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/index.ts)
- [src/adapter/bun/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/websocket.ts)
- [src/adapter/bun/serve-static.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/serve-static.ts)
- [src/helper/streaming/sse.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts)
- [src/adapter/cloudflare-workers/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/index.ts)
- [src/adapter/bun/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts)
- [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts)
- [src/adapter/deno/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/websocket.ts)
- [src/adapter/deno/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/index.ts)
- [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts)
- [src/adapter/cloudflare-pages/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/index.ts)
- [src/adapter/cloudflare-workers/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/websocket.ts)
- [src/adapter/deno/serve-static.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/serve-static.ts)
- [src/adapter/bun/server.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/server.ts)
- [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts)
- [src/helper/streaming/stream.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/stream.ts)
- [src/adapter/vercel/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/index.ts)
- [src/middleware/serve-static/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/serve-static/index.ts)
- [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json)
- [src/helper/websocket/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/websocket/index.ts)
- [src/adapter/service-worker/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/index.ts)
- [src/adapter/cloudflare-workers/serve-static-module.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/serve-static-module.ts)
- [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts)
- [src/adapter/bun/ssg.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/ssg.ts)
- [src/helper/adapter/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts)
- [runtime-tests/workerd/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/workerd/index.ts)
- [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts)
- [src/adapter/vercel/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/handler.ts)
- [src/adapter/service-worker/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/handler.ts)
- [src/adapter/cloudflare-workers/serve-static.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/serve-static.ts)
## Overview
The Bun adapter package exposes public barrel exports including `serveStatic`, `bunFileSystemModule`, `toSSG`, `createBunWebSocket`, `upgradeWebSocket`, `websocket`, `getConnInfo`, and `getBunServer`.
Sources: [src/adapter/bun/index.ts:1-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/index.ts#L1-L11)
The adapter retrieves the running Bun server instance from [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) via `getBunServer`, accessing underlying request IP functions and WebSocket server upgrade capabilities.
Sources: [src/adapter/bun/server.ts:1-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/server.ts#L1-L14), [src/adapter/bun/websocket.ts:48-72](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/websocket.ts#L48-L72), [src/adapter/bun/conninfo.ts:10-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L10-L28)
Static asset middleware integrates with [Static File Serving](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-file-serving) through `Bun.file` and Node.js filesystem helpers to check paths, determine directories, and serve content.
Sources: [src/adapter/bun/serve-static.ts:1-31](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/serve-static.ts#L1-L31)
Connection metadata extraction parses server remote address and socket details into standardized IP structures using Bun's `requestIP` API.
Sources: [src/adapter/bun/conninfo.ts:10-43](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L10-L43)
[Static site generation](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-site-generation) is supported via experimental filesystem bindings and `toSSG` adapters that interface directly with Bun's native write methods.
Sources: [src/adapter/bun/ssg.ts:1-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/ssg.ts#L1-L27)
## Entry point and module exports
### Public Module Surface
The Bun adapter package exports functions, modules, and type definitions that bridge Hono with the Bun runtime environment. These modules include static asset serving, SSG integration, WebSocket management, connection information extraction, and server instance retrieval.
Sources: [src/adapter/bun/index.ts:1-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/index.ts#L1-L11)
| Export Symbol | Export Type | Source Module | Purpose |
| --- | --- | --- | --- |
| `serveStatic` | Function | `./serve-static` | Serves static assets using Bun file system APIs |
| `bunFileSystemModule` | Object | `./ssg` | Provides filesystem bindings for static site generation |
| `toSSG` | Function | `./ssg` | Generates static site outputs via Bun filesystem integration |
| `createBunWebSocket` | Function | `./websocket` | Creates a Bun-specific WebSocket handler and upgrade pair |
| `upgradeWebSocket` | Function | `./websocket` | Upgrades HTTP requests to WebSockets on Bun |
| `websocket` | Object | `./websocket` | WebSocket configuration helper object |
| `BunWebSocketData` | Type | `./websocket` | Type definition for Bun WebSocket state data |
| `BunWebSocketHandler` | Type | `./websocket` | Type definition for Bun WebSocket event handlers |
| `getConnInfo` | Function | `./conninfo` | Extracts remote connection metadata from requests |
| `getBunServer` | Function | `./server` | Retrieves the running Bun server instance from execution context |
Sources: [src/adapter/bun/index.ts:1-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/index.ts#L1-L11)
> [!NOTE]
> All exports from `src/adapter/bun/index.ts` are re-exported at the package root to provide direct access to Bun-specific features without deep import paths.
> Sources: [src/adapter/bun/index.ts:1-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/index.ts#L1-L11)
## Native Bun server reference management
### Server Retrieval via getBunServer
The `getBunServer` helper function extracts the active Bun server instance from an [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) `Context` object. It accepts a generic type parameter `T` representing the specific Bun server type and inspects the context environment bindings (`c.env`) to locate the server reference.
Sources: [src/adapter/bun/server.ts:1-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/server.ts#L1-L14)
```typescript
export const getBunServer = (c: Context): T | undefined =>
('server' in c.env ? c.env.server : c.env) as T | undefined
```
Sources: [src/adapter/bun/server.ts:1-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/server.ts#L1-L14)
> [!NOTE]
> The function checks whether the `server` property exists directly on `c.env`. If present, it returns `c.env.server`; otherwise, it falls back to treating `c.env` itself as the server instance, casting the result to type `T | undefined`.
> Sources: [src/adapter/bun/server.ts:13-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/server.ts#L13-L14)
## Static asset resolution via Bun.file
### Middleware Integration and Native Handlers
The Bun adapter provides a specialized `serveStatic` middleware function that wraps Hono's base static asset handler (`baseServeStatic`) from [Static File Serving](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-file-serving). It injects Bun-specific file system primitives (`Bun.file`) and Node.js `fs/promises` utilities to resolve file existence, query directory status, and join paths.
Sources: [src/adapter/bun/serve-static.ts:1-31](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/serve-static.ts#L1-L31)
```typescript
export const serveStatic = (
options: ServeStaticOptions = {}
): MiddlewareHandler => {
return async function serveStatic(c, next) {
const getContent = async (path: string) => {
// @ts-ignore
const file = Bun.file(path)
return (await file.exists()) ? file : null
}
const isDir = async (path: string) => {
let isDir
try {
const stats = await stat(path)
isDir = stats.isDirectory()
} catch {}
return isDir
}
return baseServeStatic({
...options,
getContent,
join,
isDir,
})(c, next)
}
}
```
Sources: [src/adapter/bun/serve-static.ts:8-31](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/serve-static.ts#L8-L31)
> [!NOTE]
> The `getContent` closure calls `Bun.file(path)` and evaluates `file.exists()`, returning the Bun file handle if present or `null` otherwise. Directory checking (`isDir`) uses `node:fs/promises` `stat` wrapped in a try/catch block to safely handle missing paths without throwing unhandled exceptions.
> Sources: [src/adapter/bun/serve-static.ts:12-24](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/serve-static.ts#L12-L24)
## Connection info extraction
### Server Request Metadata and Remote Address Mapping
The Bun adapter implements connection metadata extraction through the `getConnInfo` function, which conforms to the `GetConnInfo` helper signature. It retrieves the underlying Bun server instance via `getBunServer` with typed constraints for `requestIP`, ensuring that runtime execution environments supply the required second argument to `fetch`.
Sources: [src/adapter/bun/conninfo.ts:10-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L10-L42)
```typescript
export const getConnInfo: GetConnInfo = (c: Context) => {
const server = getBunServer<{
requestIP?: (req: Request) => {
address: string
family: string
port: number
} | null
}>(c)
if (!server) {
throw new TypeError('env has to include the 2nd argument of fetch.')
}
if (typeof server.requestIP !== 'function') {
throw new TypeError('server.requestIP is not a function.')
}
// https://bun.sh/docs/runtime/http/server#server-requestip-request
// Returns null for closed requests or Unix domain sockets.
const info = server.requestIP(c.req.raw)
if (!info) {
return {
remote: {},
}
}
return {
remote: {
address: info.address,
addressType: info.family === 'IPv6' || info.family === 'IPv4' ? info.family : undefined,
port: info.port,
},
}
```
Sources: [src/adapter/bun/conninfo.ts:10-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L10-L42)
> [!WARNING]
> If `c.env` lacks a server reference or `server.requestIP` is not a function, `getConnInfo` throws a `TypeError`. This occurs when requests are processed without binding the Bun server instance to the execution context.
> Sources: [src/adapter/bun/conninfo.ts:19-24](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L19-L24)
### Socket Family Validation and Fallback Handling
The function invokes `server.requestIP(c.req.raw)` to query client connection properties. When operating over Unix domain sockets or processing closed requests, `requestIP` returns `null`, causing `getConnInfo` to return an empty remote object `{ remote: {} }`.
Sources: [src/adapter/bun/conninfo.ts:28-34](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L28-L34)
When valid socket information is returned, the adapter maps the properties to a standardized structure. The `addressType` field explicitly validates that the family string equals `'IPv6'` or `'IPv4'`, assigning `undefined` for any unrecognized socket family.
Sources: [src/adapter/bun/conninfo.ts:36-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L36-L42)
## Static site generation support
### Filesystem Modules and SSG Integration
The Bun adapter provides experimental static site generation bindings that bridge Hono's base SSG helper with Bun's high-performance file system APIs. The `bunFileSystemModule` defines a custom `FileSystemModule` interface implementation using Bun's native `write` method for writing build outputs.
Sources: [src/adapter/bun/ssg.ts:1-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/ssg.ts#L1-L19)
```typescript
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { toSSG as baseToSSG } from '../../helper/ssg'
import type { FileSystemModule, ToSSGAdaptorInterface } from '../../helper/ssg'
// @ts-ignore
const { write } = Bun
/**
* @experimental
* `bunFileSystemModule` is an experimental feature.
* The API might be changed.
*/
export const bunFileSystemModule: FileSystemModule = {
writeFile: async (path, data) => {
await write(path, data)
},
mkdir: async () => {},
}
```
Sources: [src/adapter/bun/ssg.ts:1-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/ssg.ts#L1-L19)
> [!WARNING]
> Both `bunFileSystemModule` and the `toSSG` adaptor function are marked as experimental. Their underlying APIs are subject to change in future releases.
> Sources: [src/adapter/bun/ssg.ts:8-12](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/ssg.ts#L8-L12), [src/adapter/bun/ssg.ts:20-24](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/ssg.ts#L20-L24)
### SSG Adapter Interface Execution
The adapter exports a `toSSG` function matching the `ToSSGAdaptorInterface` signature. It delegates execution to the core `baseToSSG` helper, passing the application instance, the Bun-specific filesystem module, and user-provided generation options.
Sources: [src/adapter/bun/ssg.ts:20-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/ssg.ts#L20-L27)
```typescript
/**
* @experimental
* `toSSG` is an experimental feature.
* The API might be changed.
*/
export const toSSG: ToSSGAdaptorInterface = async (app, options) => {
return baseToSSG(app, bunFileSystemModule, options)
}
```
Sources: [src/adapter/bun/ssg.ts:20-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/ssg.ts#L20-L27)
## Related
- [WebSocket Support](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/websocket-support)
- [Static File Serving](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-file-serving)
---
## Technical docs: Deno Adapter
URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/runtime-adapters/deno-adapter
Relevant source files
The following files were used as context for generating this wiki page:
- [src/adapter/deno/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/index.ts)
- [src/adapter/deno/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/websocket.ts)
- [src/adapter/deno/serve-static.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/serve-static.ts)
- [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts)
- [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts)
- [src/adapter/deno/deno.d.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/deno.d.ts)
- [src/adapter/bun/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/index.ts)
- [src/adapter/cloudflare-workers/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/index.ts)
- [src/adapter/deno/ssg.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/ssg.ts)
- [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts)
- [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts)
- [src/adapter/bun/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/websocket.ts)
- [src/helper/ssg/ssg.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/ssg.ts)
- [src/middleware/serve-static/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/serve-static/index.ts)
- [src/adapter/service-worker/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/index.ts)
- [src/adapter/cloudflare-pages/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/index.ts)
- [src/hono.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono.ts)
- [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json)
- [src/adapter/deno/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/conninfo.ts)
- [src/helper/proxy/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts)
- [src/adapter/bun/serve-static.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/serve-static.ts)
- [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts)
- [src/adapter/cloudflare-workers/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/websocket.ts)
- [src/adapter/vercel/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/handler.ts)
- [src/adapter/service-worker/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/handler.ts)
- [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts)
- [src/helper/websocket/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/websocket/index.ts)
- [src/adapter/vercel/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/index.ts)
- [src/helper/adapter/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts)
- [runtime-tests/workerd/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/workerd/index.ts)
## Overview
The Deno Adapter provides runtime integration for running Hono applications within the Deno environment. It bridges Hono's middleware and helper systems with Deno-specific platform APIs, exposing modules for [static file serving](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-file-serving), WebSocket upgrading, [static site generation](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-site-generation), and connection network metadata extraction.
Sources: [src/adapter/deno/index.ts:1-9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/index.ts#L1-L9)
## Module exports and entry points
### Public API Surface
The `hono/deno` entry point exposes specific utility modules designed for the Deno runtime environment. These exports bridge standard Hono mechanics with Deno platform features such as file system-based static asset delivery, static site generation module bindings, WebSocket connection upgrades, and remote connection metadata retrieval.
| Export Name | Source Module | Purpose |
| --- | --- | --- |
| `serveStatic` | `./serve-static` | Serves static files from the Deno file system [Static Site Generation](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-site-generation) |
| `toSSG` | `./ssg` | Generates static sites using Deno file system bindings |
| `denoFileSystemModule` | `./ssg` | Provides Deno file system methods for static site generation output |
| `upgradeWebSocket` | `./websocket` | Upgrades standard HTTP connections to Deno WebSocket streams |
| `getConnInfo` | `./conninfo` | Extracts remote client network metadata from Deno incoming connections |
Sources: [src/adapter/deno/index.ts:1-9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/index.ts#L1-L9)
### Runtime Environment Detection
The adapter helper module defines the runtime identifier `'deno'` alongside other supported execution engines. When evaluating runtime environments through `getRuntimeKey`, the Deno runtime is identified by matching the `navigator.userAgent` string against known user agent configurations.
| Runtime Key | User Agent String / Detection Criteria |
| --- | --- |
| `deno` | `Deno` |
| `bun` | `Bun` |
| `workerd` | `Cloudflare-Workers` |
| `node` | `Node.js` |
| `edge-light` | `global.EdgeRuntime` string presence |
| `fastly` | `global.fastly` definition check |
| `other` | Fallback when no specific runtime matches |
Sources: [src/helper/adapter/index.ts:43-84](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L43-L84)
> [!NOTE]
> Environment variable resolution in the adapter helper accesses `Deno.env.toObject()` when the runtime key resolves to `'deno'`, mapping runtime configuration directly into typed bindings.
Sources: [src/helper/adapter/index.ts:29-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L29-L33)
## Serving static files from disk
### File System Adapter Integration
The `serveStatic` helper in `src/adapter/deno/serve-static.ts` wraps Hono's core `baseServeStatic` middleware from `src/middleware/serve-static` to deliver assets directly from the Deno file system. It destructs `open`, `lstatSync`, and `errors` from the global `Deno` namespace to handle file resolution and directory checks.
```typescript
const { open, lstatSync, errors } = Deno
export const serveStatic = (
options: ServeStaticOptions = {}
): MiddlewareHandler => {
return async function serveStatic(c, next) {
const getContent = async (path: string) => {
try {
if (isDir(path)) {
return null
}
const file = await open(path)
return file.readable
} catch (e) {
if (!(e instanceof errors.NotFound)) {
console.warn(`${e}`)
}
return null
}
}
const isDir = (path: string) => {
let isDir
try {
const stat = lstatSync(path)
isDir = stat.isDirectory
} catch {}
return isDir
}
return baseServeStatic({
...options,
getContent,
join,
isDir,
})(c, next)
}
}
```
Sources: [src/adapter/deno/serve-static.ts:6-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/serve-static.ts#L6-L42)
### Asset Resolution and Error Handling
When a request arrives, `getContent` first checks whether the target path points to a directory using the internal `isDir` helper backed by `Deno.lstatSync`. If the path represents a directory, `getContent` returns `null` immediately to trigger directory index fallback or routing continuation. Otherwise, it attempts to open the file via `Deno.open` and returns its `.readable` stream property.
```typescript
const getContent = async (path: string) => {
try {
if (isDir(path)) {
return null
}
const file = await open(path)
return file.readable
} catch (e) {
if (!(e instanceof errors.NotFound)) {
console.warn(`${e}`)
}
return null
}
}
const isDir = (path: string) => {
let isDir
try {
const stat = lstatSync(path)
isDir = stat.isDirectory
} catch {}
return isDir
}
```
Sources: [src/adapter/deno/serve-static.ts:12-34](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/serve-static.ts#L12-L34)
> [!WARNING]
> Any caught exception during file opening that is not an instance of `Deno.errors.NotFound` is logged via `console.warn`, whereas `NotFound` errors are silently ignored to allow clean fallback handling by downstream middleware.
Sources: [src/adapter/deno/serve-static.ts:20-25](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/serve-static.ts#L20-L25)
## WebSocket upgrade integration
### Upgrade Mechanism and Subprotocol Negotiation
The `upgradeWebSocket` helper wraps Hono's `defineWebSocketHelper` to handle full-duplex WebSocket connections in Deno. It first inspects the incoming request headers; if the `upgrade` header does not equal `'websocket'`, the helper returns `undefined` to let standard HTTP request handling proceed.
```typescript
export const upgradeWebSocket: UpgradeWebSocket =
defineWebSocketHelper(async (c, events, options) => {
if (c.req.header('upgrade') !== 'websocket') {
return
}
```
Sources: [src/adapter/deno/websocket.ts:4-9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/websocket.ts#L4-L9)
To ensure browser compatibility, the helper extracts the first requested subprotocol from the `sec-websocket-protocol` header. Echoing this subprotocol back prevents connection rejections in strict clients such as Google Chrome when subprotocols are negotiated.
```typescript
// Echo the negotiated subprotocol back to the client. Browsers (e.g. Chrome)
// reject the connection when a subprotocol was requested but the response is
// missing the `Sec-WebSocket-Protocol` header.
const subprotocol = c.req.header('sec-websocket-protocol')?.split(',')[0]?.trim()
const { response, socket } = Deno.upgradeWebSocket(c.req.raw, {
...(subprotocol ? { protocol: subprotocol } : {}),
...options,
})
```
Sources: [src/adapter/deno/websocket.ts:10-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/websocket.ts#L10-L18)
> [!NOTE]
> The `Deno.upgradeWebSocket` function accepts `req` along with `UpgradeWebSocketOptions`, returning an object containing both the HTTP `response` and the underlying `socket`.
Sources: [src/adapter/deno/websocket.ts:15-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/websocket.ts#L15-L18), [src/adapter/deno/deno.d.ts:49-55](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/deno.d.ts#L49-L55)
### WSContext Event Bridging
Once the native socket is established, `upgradeWebSocket` instantiates a `WSContext` wrapper that maps property getters and methods onto the Deno socket. It wires event handlers `onopen`, `onmessage`, `onclose`, and `onerror` directly to the corresponding callbacks defined in the event parameter object.
```typescript
const wsContext: WSContext = new WSContext({
close: (code, reason) => socket.close(code, reason),
get protocol() {
return socket.protocol
},
raw: socket,
get readyState() {
return socket.readyState as WSReadyState
},
url: socket.url ? new URL(socket.url) : null,
send: (source) => socket.send(source),
})
socket.onopen = (evt) => events.onOpen?.(evt, wsContext)
socket.onmessage = (evt) => events.onMessage?.(evt, wsContext)
socket.onclose = (evt) => events.onClose?.(evt, wsContext)
socket.onerror = (evt) => events.onError?.(evt, wsContext)
return response
```
Sources: [src/adapter/deno/websocket.ts:20-37](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/websocket.ts#L20-L37)
The configuration options accepted by Deno's WebSocket upgrade routine are typed through `Deno.UpgradeWebSocketOptions`, supporting protocol selection and idle timeout configuration.
| Option | Type | Default | Purpose |
| --- | --- | --- | --- |
| `protocol` | `string` | — | Sets the `.protocol` property on the client-side WebSocket to match requested subprotocols |
| `idleTimeout` | `number` | `30` | Maximum seconds without a pong frame before connection is deemed unhealthy and closed; set to `0` to disable |
Sources: [src/adapter/deno/deno.d.ts:60-78](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/deno.d.ts#L60-L78)
## Extracting connection network metadata
### Connection Info Helper Signature and Environment Binding
The `getConnInfo` helper extracts remote client connection metadata from the [execution context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) in Deno environments. It conforms to the `GetConnInfo` type definition and reads `remoteAddr` directly from the environment bindings property `c.env`.
```typescript
import type { GetConnInfo } from '../../helper/conninfo'
/**
* Get conninfo with Deno
* @param c Context
* @returns ConnInfo
*/
export const getConnInfo: GetConnInfo = (c) => {
const { remoteAddr } = c.env
return {
remote: {
address: remoteAddr.hostname,
port: remoteAddr.port,
transport: remoteAddr.transport,
},
}
```
Sources: [src/adapter/deno/conninfo.ts:1-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/conninfo.ts#L1-L16)
### Remote Address Mapping
The function returns a structured `ConnInfo` object containing a nested `remote` object. It maps property values from the Deno `remoteAddr` instance to standard address fields.
| Field | Source Property | Type / Description |
| --- | --- | --- |
| `address` | `remoteAddr.hostname` | Remote IP address or hostname of the connected client |
| `port` | `remoteAddr.port` | Network port number used by the client connection |
| `transport` | `remoteAddr.transport` | Underlying transport protocol (`tcp` or `udp`) |
Sources: [src/adapter/deno/conninfo.ts:8-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/conninfo.ts#L8-L16)
> [!NOTE]
> `getConnInfo` assumes that `c.env` provides a populated `remoteAddr` object with `hostname`, `port`, and `transport` properties matching Deno's network address structure.
Sources: [src/adapter/deno/conninfo.ts:8-15](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/conninfo.ts#L8-L15)
## Static site generation with Deno
### File System Module Integration
The `hono/deno` adapter integrates with static site generation by wiring Deno native file system APIs into Hono's core SSG framework. The `denoFileSystemModule` object satisfies the `FileSystemModule` interface by implementing file writing and directory creation primitives.
```typescript
export const denoFileSystemModule: FileSystemModule = {
writeFile: async (path, data) => {
const uint8Data =
typeof data === 'string' ? new TextEncoder().encode(data) : new Uint8Array(data)
await Deno.writeFile(path, uint8Data)
},
mkdir: async (path, options) => {
return Deno.mkdir(path, { recursive: options?.recursive ?? false })
},
}
```
Sources: [src/adapter/deno/ssg.ts:9-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/ssg.ts#L9-L18)
When `writeFile` is invoked, it checks whether the provided data is a string; if so, it encodes the text into a `Uint8Array` using `TextEncoder`, otherwise it wraps or casts the input data as a `Uint8Array` before calling `Deno.writeFile`. The `mkdir` method forwards directory creation requests to `Deno.mkdir`, defaulting the recursive flag to `false` if options are omitted.
```typescript
writeFile: async (path, data) => {
const uint8Data =
typeof data === 'string' ? new TextEncoder().encode(data) : new Uint8Array(data)
await Deno.writeFile(path, uint8Data)
},
mkdir: async (path, options) => {
return Deno.mkdir(path, { recursive: options?.recursive ?? false })
},
```
Sources: [src/adapter/deno/ssg.ts:10-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/ssg.ts#L10-L17)
> [!NOTE]
> Both `denoFileSystemModule` and the `toSSG` export are marked as experimental features whose APIs may change in future releases.
Sources: [src/adapter/deno/ssg.ts:4-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/ssg.ts#L4-L8), [src/adapter/deno/ssg.ts:20-24](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/ssg.ts#L20-L24)
### SSG Execution Function
The `toSSG` adapter function matches the `ToSSGAdaptorInterface` signature, taking a Hono application instance and generation options, and delegating execution to the base `toSSG` utility bundled with `denoFileSystemModule`.
```typescript
export const toSSG: ToSSGAdaptorInterface = async (app, options) => {
return baseToSSG(app, denoFileSystemModule, options)
}
```
Sources: [src/adapter/deno/ssg.ts:25-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/ssg.ts#L25-L27)
## Related
- [WebSocket Support](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/websocket-support)
- [Static File Serving](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-file-serving)
---
## Technical docs: JWT and JWK
URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/jwt-and-jwk
Relevant source files
The following files were used as context for generating this wiki page:
- [src/utils/jwt/jwt.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts)
- [src/utils/jwt/jws.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts)
- [src/middleware/jwk/jwk.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/jwk.ts)
- [src/middleware/secure-headers/secure-headers.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts)
- [src/middleware/jwk/keys.test.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/keys.test.json)
- [src/middleware/jwt/jwt.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts)
- [src/middleware/bearer-auth/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts)
- [src/middleware/cache/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts)
- [src/middleware/basic-auth/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts)
- [src/middleware/csrf/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts)
- [src/middleware/etag/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts)
- [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts)
- [src/helper/cookie/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/cookie/index.ts)
- [src/utils/jwt/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/types.ts)
- [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts)
- [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts)
- [src/middleware/jwk/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/index.ts)
- [src/utils/crypto.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/crypto.ts)
- [src/middleware/language/language.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts)
- [src/utils/jwt/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/index.ts)
- [src/client/fetch-result-please.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/client/fetch-result-please.ts)
- [src/middleware/jwt/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/index.ts)
- [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json)
- [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts)
- [src/utils/cookie.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/cookie.ts)
- [src/utils/jwt/jwa.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwa.ts)
- [src/utils/jwt/utf8.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/utf8.ts)
- [jsr.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json)
- [src/router/linear-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/index.ts)
- [src/helper/accepts/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/accepts/index.ts)
## Overview
Hono provides native JSON Web Token (JWT) and JSON Web Key (JWK) utilities alongside dedicated middleware handlers to authenticate HTTP requests securely across Web Standard runtimes. By leveraging `crypto.subtle`, the implementation handles cryptographic signing, signature verification, and dynamic key resolution without external cryptographic dependencies.
Sources: [src/utils/jwt/jwt.ts:1-29](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L1-L29), [src/utils/jwt/jws.ts:1-12](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts#L1-L12), [src/middleware/jwt/jwt.ts:1-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L1-L20), [src/middleware/jwk/jwk.ts:1-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/jwk.ts#L1-L16)
## Token Signing and Key Resolution
### Signing Workflow and Serialisation
Token generation begins by serialising the payload and header objects into Base64Url-encoded strings without padding. The `sign` function first encodes the `JWTPayload` object using `encodeJwtPart`, which converts the JSON-serialised payload into UTF-8 bytes and transforms it via `encodeBase64Url`, stripping any trailing `=` characters.
```typescript
const encodeJwtPart = (part: unknown): string =>
encodeBase64Url(utf8Encoder.encode(JSON.stringify(part)).buffer).replace(/=/g, '')
const encodeSignaturePart = (buf: ArrayBufferLike): string => encodeBase64Url(buf).replace(/=/g, '')
```
Sources: [src/utils/jwt/jwt.ts:31-34](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L31-L34)
Next, the header is constructed. If the supplied `privateKey` is an object containing an `alg` property, the algorithm and optional `kid` (Key ID) are extracted into the header. Otherwise, the provided algorithm parameter (defaulting to `'HS256'`) is used alongside `typ: 'JWT'`. The header and payload are concatenated with a dot delimiter (`${encodedHeader}.${encodedPayload}`) to form the partial token.
```typescript
export const sign = async (
payload: JWTPayload,
privateKey: SignatureKey,
alg: SignatureAlgorithm = 'HS256'
): Promise => {
const encodedPayload = encodeJwtPart(payload)
let encodedHeader
if (typeof privateKey === 'object' && 'alg' in privateKey) {
alg = privateKey.alg as SignatureAlgorithm
encodedHeader = encodeJwtPart({ alg, typ: 'JWT', kid: privateKey.kid })
} else {
encodedHeader = encodeJwtPart({ alg, typ: 'JWT' })
}
const partialToken = `${encodedHeader}.${encodedPayload}`
const signaturePart = await signing(privateKey, alg, utf8Encoder.encode(partialToken))
const signature = encodeSignaturePart(signaturePart)
return `${partialToken}.${signature}`
}
```
Sources: [src/utils/jwt/jwt.ts:56-76](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L56-L76)
### Call-Chain Execution Walkthrough
When `sign` invokes the signing routine, execution flows through the JWS and Web Crypto resolution layers.
1. `sign` in `src/utils/jwt/jwt.ts` invokes `signing` with the private key, algorithm identifier, and encoded partial token bytes.
2. `signing` in `src/utils/jwt/jws.ts` calls `getKeyAlgorithm(alg)` to map the string algorithm to a Web Crypto `KeyAlgorithm` parameter structure.
3. `getKeyAlgorithm` inspects the algorithm name; if an unsupported identifier is supplied, it falls through or throws `JwtAlgorithmNotImplemented`.
4. `signing` then calls `importPrivateKey(privateKey, algorithm)` to prepare the cryptographic key instance.
5. `crypto.subtle.sign` executes against the imported `CryptoKey` to produce the raw signature buffer, which is subsequently encoded and appended to the token string.
```mermaid
sequenceDiagram
participant jwt.ts
participant jws.ts
participant jwa.ts
participant types.ts
jwt.ts->>jws.ts: signing(privateKey, alg, data)
jws.ts->>jws.ts: getKeyAlgorithm(alg)
alt algorithm unsupported
jwa.ts-->>types.ts: JwtAlgorithmNotImplemented
end
jws.ts->>jws.ts: importPrivateKey(privateKey, algorithm)
jws.ts->>crypto.subtle: sign(algorithm, cryptoKey, data)
crypto.subtle-->>jws.ts: ArrayBuffer signature
jws.ts-->>jwt.ts: raw signature buffer
```
Sources: [src/utils/jwt/jwt.ts:72-72](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L72-L72), [src/utils/jwt/jws.ts:29-37](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts#L29-L37), [src/utils/jwt/jws.ts:122-179](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts#L122-L179), [src/utils/jwt/types.ts:6-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/types.ts#L6-L11)
### Web Crypto Key Resolution
The `importPrivateKey` function handles diverse key representations, including raw strings, PEM-encoded structures, JWK objects, and existing `CryptoKey` instances. It ensures that the resulting key is assigned the `CryptoKeyUsage.Sign` usage flag.
```typescript
async function importPrivateKey(key: SignatureKey, alg: KeyImporterAlgorithm): Promise {
if (!crypto.subtle || !crypto.subtle.importKey) {
throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')
}
if (isCryptoKey(key)) {
if (key.type !== 'private' && key.type !== 'secret') {
throw new Error(
`unexpected key type: CryptoKey.type is ${key.type}, expected private or secret`
)
}
return key
}
const usages = [CryptoKeyUsage.Sign]
if (typeof key === 'object') {
return await crypto.subtle.importKey('jwk', key, alg, false, usages)
}
if (key.includes('PRIVATE')) {
return await crypto.subtle.importKey('pkcs8', pemToBinary(key), alg, false, usages)
}
return await crypto.subtle.importKey('raw', utf8Encoder.encode(key), alg, false, usages)
}
```
Sources: [src/utils/jwt/jws.ts:54-76](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts#L54-L76)
> [!WARNING]
> When passing an existing `CryptoKey` to `importPrivateKey`, its `type` property must be either `'private'` or `'secret'`. Passing a public key where a private or secret key is required causes an immediate error.
Sources: [src/utils/jwt/jws.ts:58-64](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts#L58-L64)
## Token Verification and Claims Validation
### Claims Verification Options
Token validation begins with structural decoding and signature verification, separating cryptographic checks from payload claims assertions. The `decode` function splits the token by periods, verifying that exactly three parts exist before parsing the header and payload components.
Sources: [src/utils/jwt/jwt.ts:264-279](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L264-L279)
```typescript
export const decode = (token: string): { header: TokenHeader; payload: JWTPayload } => {
const parts = token.split('.')
if (parts.length !== 3) {
throw new JwtTokenInvalid(token)
}
try {
const header = decodeJwtPart(parts[0]) as TokenHeader
const payload = decodeJwtPart(parts[1]) as JWTPayload
return {
header,
payload,
}
} catch {
throw new JwtTokenInvalid(token)
}
}
```
Sources: [src/utils/jwt/jwt.ts:264-279](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L264-L279)
The `VerifyOptions` type configures how standard registered claims are validated against the current system time and expected constraints during token verification.
Sources: [src/utils/jwt/jwt.ts:78-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L78-L94)
| Option | Type | Default | Purpose |
| :--- | :--- | :--- | :--- |
| `iss` | `string \| RegExp` | — | Expected issuer used for verifying the `iss` claim |
| `nbf` | `boolean` | `true` | Verify that the current timestamp is after or equal to the `nbf` claim |
| `exp` | `boolean` | `true` | Verify that the current timestamp is before the `exp` claim |
| `iat` | `boolean` | `true` | Verify that the `iat` claim is a valid number not in the future |
| `aud` | `string \| string[] \| RegExp` | — | Expected audience used for verifying the `aud` claim |
| `alg` | `SignatureAlgorithm` | — | Required signature algorithm for verification |
Sources: [src/utils/jwt/jwt.ts:78-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L78-L94)
> [!NOTE]
> If the `alg` option is omitted during verification, the verifier immediately throws a `JwtAlgorithmRequired` error to prevent algorithm substitution vulnerabilities.
Sources: [src/utils/jwt/jwt.ts:99-101](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L99-L101)
## JSON Web Key Set Middleware
### JWKS Retrieval and Key Matching
The `verifyWithJwks` function retrieves and validates JSON Web Key Sets (JWKS) to verify incoming tokens without pre-configured static keys. It first decodes the token header and checks for a valid header structure and a mandatory `kid` (Key ID) property. If the header lacks a `kid`, `JwtHeaderRequiresKid` is thrown.
Sources: [src/utils/jwt/jwt.ts:209-216](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L209-L216)
```typescript
export const verifyWithJwks = async (
token: string,
options: {
keys?: HonoJsonWebKey[]
jwks_uri?: string
verification?: VerifyOptions
allowedAlgorithms: readonly AsymmetricAlgorithm[]
},
init?: RequestInit
): Promise => {
const verifyOpts = options.verification || {}
const header = decodeHeader(token)
if (!isTokenHeader(header)) {
throw new JwtHeaderInvalid(header)
}
if (!header.kid) {
throw new JwtHeaderRequiresKid(header)
}
```
Sources: [src/utils/jwt/jwt.ts:197-216](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L197-L216)
> [!WARNING]
> Symmetric algorithms such as `HS256`, `HS384`, and `HS512` are explicitly prohibited during JWKS verification. Any token header using a symmetric algorithm causes `verifyWithJwks` to throw a `JwtSymmetricAlgorithmNotAllowed` error to prevent algorithm confusion attacks.
Sources: [src/utils/jwt/jwt.ts:190-221](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L190-L221)
```typescript
// Reject symmetric algorithms (HS256, HS384, HS512) to prevent algorithm confusion attacks
if (symmetricAlgorithms.includes(header.alg as SymmetricAlgorithm)) {
throw new JwtSymmetricAlgorithmNotAllowed(header.alg)
}
// Validate against allowed algorithms
if (!options.allowedAlgorithms.includes(header.alg as AsymmetricAlgorithm)) {
throw new JwtAlgorithmNotAllowed(header.alg, options.allowedAlgorithms)
}
```
Sources: [src/utils/jwt/jwt.ts:218-226](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L218-L226)
When an `options.jwks_uri` is supplied, `verifyWithJwks` fetches the URI using the optional `RequestInit` init argument, parses the JSON response, and ensures that a `keys` array exists. These fetched keys are merged with any statically provided `options.keys`. The verifier then finds the specific key where `key.kid === header.kid`.
Sources: [src/utils/jwt/jwt.ts:228-251](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L228-L251)
```typescript
let verifyKeys = options.keys ? [...options.keys] : undefined
if (options.jwks_uri) {
const response = await fetch(options.jwks_uri, init)
if (!response.ok) {
throw new Error(`failed to fetch JWKS from ${options.jwks_uri}`)
}
const data = (await response.json()) as { keys?: JsonWebKey[] }
if (!data.keys) {
throw new Error('invalid JWKS response. "keys" field is missing')
}
if (!Array.isArray(data.keys)) {
throw new Error('invalid JWKS response. "keys" field is not an array')
}
verifyKeys ??= []
verifyKeys.push(...(data.keys as HonoJsonWebKey[]))
} else if (!verifyKeys) {
throw new Error('verifyWithJwks requires options for either "keys" or "jwks_uri" or both')
}
const matchingKey = verifyKeys.find((key) => key.kid === header.kid)
if (!matchingKey) {
throw new JwtTokenInvalid(token)
}
// Verify that JWK's alg matches JWT header's alg when JWK has alg field
if (matchingKey.alg && matchingKey.alg !== header.alg) {
throw new JwtAlgorithmMismatch(matchingKey.alg, header.alg)
}
return await verify(token, matchingKey, {
alg: header.alg,
...verifyOpts,
})
}
```
Sources: [src/utils/jwt/jwt.ts:228-262](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L228-L262)
### Verification Execution and Call Chain
The execution flow for JWKS-based verification proceeds through structural header inspection and key resolution.
1. `verifyWithJwks` — Entry point for verifying tokens against local keys or a remote JWKS endpoint.
Sources: [src/utils/jwt/jwt.ts:197-210](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L197-L210)
2. `decodeHeader` — Splits the token by periods and decodes the first segment into a `TokenHeader` object.
Sources: [src/utils/jwt/jwt.ts:281-290](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L281-L290)
3. `JwtTokenInvalid` — Thrown if the token does not contain exactly three parts or if part decoding fails.
Sources: [src/utils/jwt/jwt.ts:265-268](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L265-L268), [src/utils/jwt/jwt.ts:283-289](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L283-L289)
```mermaid
sequenceDiagram
participant verifyWithJwks as src/utils/jwt/jwt.ts
participant decodeHeader as src/utils/jwt/jwt.ts
participant JwtTokenInvalid as src/utils/jwt/types.ts
verifyWithJwks->>decodeHeader: decodeHeader(token)
decodeHeader->>JwtTokenInvalid: throw JwtTokenInvalid(token) if parts length !== 3
```
Sources: [src/utils/jwt/jwt.ts:209-210](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L209-L210), [src/utils/jwt/jwt.ts:281-290](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L281-L290)
> [!NOTE]
> If a matching JWK defines an explicit `alg` property, it must strictly match the `alg` declared in the JWT header. A mismatch causes a `JwtAlgorithmMismatch` exception.
Sources: [src/utils/jwt/jwt.ts:253-256](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L253-L256)
## JWT Authentication Middleware Flow
### Credential Extraction and Token Resolution
The `jwt` middleware intercepts incoming HTTP requests to locate and validate JSON Web Tokens from configured request headers or cookies. It first checks the request headers using `options.headerName` (defaulting to `'Authorization'`). When credentials are found in the header, the middleware splits the string by whitespace and expects exactly two parts where the first segment case-insensitively equals `'bearer'`. If the credential structure is invalid, it throws an `HTTPException` with status code `401`.
Sources: [src/middleware/jwt/jwt.ts:76-95](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L76-L95)
```typescript
return async function jwt(ctx, next) {
const headerName = options.headerName || 'Authorization'
const credentials = ctx.req.raw.headers.get(headerName)
let token
if (credentials) {
const parts = credentials.split(/\s+/)
if (parts.length !== 2 || parts[0].toLowerCase() !== 'bearer') {
const errDescription = 'invalid credentials structure'
throw new HTTPException(401, {
message: errDescription,
res: unauthorizedResponse({
ctx,
error: 'invalid_request',
errDescription,
}),
})
} else {
token = parts[1]
}
```
Sources: [src/middleware/jwt/jwt.ts:76-95](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L76-L95)
If no header credentials exist, the middleware evaluates `options.cookie`. The `cookie` option can be provided as a plain string key or an object containing `key`, an optional `secret` for signed cookies, and optional `prefixOptions`. Depending on these options, the token is extracted using `getCookie` or `getSignedCookie`.
Sources: [src/middleware/jwt/jwt.ts:96-117](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L96-L117)
```typescript
} else if (options.cookie) {
if (typeof options.cookie == 'string') {
token = getCookie(ctx, options.cookie)
} else if (options.cookie.secret) {
if (options.cookie.prefixOptions) {
token = await getSignedCookie(
ctx,
options.cookie.secret,
options.cookie.key,
options.cookie.prefixOptions
)
} else {
token = await getSignedCookie(ctx, options.cookie.secret, options.cookie.key)
}
} else {
if (options.cookie.prefixOptions) {
token = getCookie(ctx, options.cookie.key, options.cookie.prefixOptions)
} else {
token = getCookie(ctx, options.cookie.key)
}
}
}
```
Sources: [src/middleware/jwt/jwt.ts:96-117](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L96-L117)
> [!WARNING]
> If neither header credentials nor a valid cookie yields a token string, the middleware immediately rejects the request with a `401` HTTP exception and an `invalid_request` error description.
Sources: [src/middleware/jwt/jwt.ts:119-129](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L119-L129)
```typescript
if (!token) {
const errDescription = 'no authorization included in request'
throw new HTTPException(401, {
message: errDescription,
res: unauthorizedResponse({
ctx,
error: 'invalid_request',
errDescription,
}),
})
}
```
Sources: [src/middleware/jwt/jwt.ts:119-129](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L119-L129)
### Verification, Context Injection, and 401 Responses
Once a token is extracted, the middleware invokes `Jwt.verify` with the configured `secret`, `alg`, and verification options. If verification fails or throws an error, a `401` exception is raised with an `invalid_token` error and a `WWW-Authenticate` challenge header. Upon successful verification, the decoded payload is stored in the [execution context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) under the key `'jwtPayload'`, and control proceeds to the next handler via `await next()`.
Sources: [src/middleware/jwt/jwt.ts:131-157](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L131-L157)
```typescript
let payload
let cause
try {
payload = await Jwt.verify(token, options.secret, {
alg: options.alg,
...verifyOpts,
})
} catch (e) {
cause = e
}
if (!payload) {
throw new HTTPException(401, {
message: 'Unauthorized',
res: unauthorizedResponse({
ctx,
error: 'invalid_token',
statusText: 'Unauthorized',
errDescription: 'token verification failure',
}),
cause,
})
}
ctx.set('jwtPayload', payload)
await next()
}
```
Sources: [src/middleware/jwt/jwt.ts:131-157](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L131-L157)
Unauthorized responses are constructed via `unauthorizedResponse`, which formats a `401` status response carrying a `WWW-Authenticate` header containing the request URL, error type, and error description.
Sources: [src/middleware/jwt/jwt.ts:160-173](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L160-L173)
```typescript
function unauthorizedResponse(opts: {
ctx: Context
error: string
errDescription: string
statusText?: string
}) {
return new Response('Unauthorized', {
status: 401,
statusText: opts.statusText,
headers: {
'WWW-Authenticate': `Bearer realm="${opts.ctx.req.url}",error="${opts.error}",error_description="${opts.errDescription}"`,
},
})
}
```
Sources: [src/middleware/jwt/jwt.ts:160-173](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L160-L173)
## Supported Cryptographic Algorithms and Errors
### Supported JWA Signature Algorithms and Web Crypto Mappings
JSON Web Algorithms (JWA) are mapped to underlying Web Crypto API operations via `getKeyAlgorithm` in the JWS utility module. Supported algorithms encompass HMAC-SHA variants (`HS256`, `HS384`, `HS512`), RSA signatures using PKCS#1 v1.5 (`RS256`, `RS384`, `RS512`), RSA Probabilistic Signature Scheme (`PS256`, `PS384`, `PS512`), and Elliptic Curve Digital Signature Algorithm variants (`ES256`, `ES384`, `ES512`) alongside `EdDSA`.
| Algorithm | JWA Category | Web Crypto Algorithm Name | Hash Function | Additional Parameters |
| :--- | :--- | :--- | :--- | :--- |
| `HS256` | Symmetric | `HMAC` | `SHA-256` | — |
| `HS384` | Symmetric | `HMAC` | `SHA-384` | — |
| `HS512` | Symmetric | `HMAC` | `SHA-512` | — |
| `RS256` | Asymmetric | `RSASSA-PKCS1-v1_5` | `SHA-256` | — |
| `RS384` | Asymmetric | `RSASSA-PKCS1-v1_5` | `SHA-384` | — |
| `RS512` | Asymmetric | `RSASSA-PKCS1-v1_5` | `SHA-512` | — |
| `PS256` | Asymmetric | `RSA-PSS` | `SHA-256` | `saltLength: 32` |
| `PS384` | Asymmetric | `RSA-PSS` | `SHA-384` | `saltLength: 48` |
| `PS512` | Asymmetric | `RSA-PSS` | `SHA-512` | `saltLength: 64` |
| `ES256` | Asymmetric | `ECDSA` | `SHA-256` | `namedCurve: 'P-256'` |
| `ES384` | Asymmetric | `ECDSA` | `SHA-384` | `namedCurve: 'P-384'` |
| `ES512` | Asymmetric | `ECDSA` | `SHA-512` | `namedCurve: 'P-521'` |
| `EdDSA` | Asymmetric | `Ed25519` | — | — |
Sources: [src/utils/jwt/jwa.ts:7-21](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwa.ts#L7-L21), [src/utils/jwt/jws.ts:122-211](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts#L122-L211)
```typescript
function getKeyAlgorithm(name: SignatureAlgorithm): KeyAlgorithm {
switch (name) {
case 'HS256':
return {
name: 'HMAC',
hash: {
name: 'SHA-256',
},
} satisfies HmacImportParams
case 'HS384':
return {
name: 'HMAC',
hash: {
name: 'SHA-384',
},
} satisfies HmacImportParams
case 'HS512':
return {
name: 'HMAC',
hash: {
name: 'SHA-512',
},
} satisfies HmacImportParams
case 'RS256':
return {
name: 'RSASSA-PKCS1-v1_5',
hash: {
name: 'SHA-256',
},
} satisfies RsaHashedImportParams
case 'RS384':
return {
name: 'RSASSA-PKCS1-v1_5',
hash: {
name: 'SHA-384',
},
} satisfies RsaHashedImportParams
case 'RS512':
return {
name: 'RSASSA-PKCS1-v1_5',
hash: {
name: 'SHA-512',
},
} satisfies RsaHashedImportParams
case 'PS256':
return {
name: 'RSA-PSS',
hash: {
name: 'SHA-256',
},
saltLength: 32, // 256 >> 3
} satisfies RsaPssParams & RsaHashedImportParams
case 'PS384':
return {
name: 'RSA-PSS',
hash: {
name: 'SHA-384',
},
saltLength: 48, // 384 >> 3
} satisfies RsaPssParams & RsaHashedImportParams
case 'PS512':
return {
name: 'RSA-PSS',
hash: {
name: 'SHA-512',
},
saltLength: 64, // 512 >> 3,
} satisfies RsaPssParams & RsaHashedImportParams
case 'ES256':
return {
name: 'ECDSA',
hash: {
name: 'SHA-256',
},
namedCurve: 'P-256',
} satisfies EcdsaParams & EcKeyImportParams
case 'ES384':
return {
name: 'ECDSA',
hash: {
```
Sources: [src/utils/jwt/jws.ts:122-211](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts#L122-L211)
> [!CAUTION]
> For `PS256`, `PS384`, and `PS512`, the salt length is strictly derived from the hash bit length divided by eight (`256 >> 3` yields `32`, `384 >> 3` yields `48`, and `512 >> 3` yields `64`). Specifying a custom or non-standard salt length outside these Web Crypto mappings will cause signature verification or generation to fail.
Sources: [src/utils/jwt/jws.ts:166-194](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts#L166-L194)
### Custom Error Types
JWT parsing, validation, and cryptographic routines throw specialized error classes defined in `src/utils/jwt/types.ts`. Each error sets a descriptive message and assigns its `name` property to match the class identifier.
| Error Class | Constructor Arguments | Error Message Pattern |
| :--- | :--- | :--- |
| `JwtAlgorithmNotImplemented` | `alg: string` | `${alg} is not an implemented algorithm` |
| `JwtAlgorithmRequired` | none | `JWT verification requires "alg" option to be specified` |
| `JwtAlgorithmMismatch` | `expected: string, actual: string` | `JWT algorithm mismatch: expected "${expected}", got "${actual}"` |
| `JwtTokenInvalid` | `token: string` | `invalid JWT token: ${token}` |
| `JwtTokenNotBefore` | `token: string` | `token (${token}) is being used before it's valid` |
| `JwtTokenExpired` | `token: string` | `token (${token}) expired` |
| `JwtTokenIssuedAt` | `currentTimestamp: number, iat: number` | `Invalid "iat" claim, must be a valid number lower than "${currentTimestamp}" (iat: "${iat}")` |
| `JwtTokenIssuer` | `expected: string \| RegExp, iss: string \| null` | `expected issuer "${expected}", got ${iss ? `"${iss}"` : 'none'} ` |
| `JwtHeaderInvalid` | `header: object` | `jwt header is invalid: ${JSON.stringify(header)}` |
| `JwtHeaderRequiresKid` | `header: object` | `required "kid" in jwt header: ${JSON.stringify(header)}` |
| `JwtSymmetricAlgorithmNotAllowed` | `alg: string` | `symmetric algorithm "${alg}" is not allowed for JWK verification` |
| `JwtAlgorithmNotAllowed` | `alg: string, allowedAlgorithms: readonly string[]` | `algorithm "${alg}" is not in the allowed list: [...]` |
| `JwtTokenSignatureMismatched` | `token: string` | `token(${token}) signature mismatched` |
| `JwtPayloadRequiresAud` | `payload: object` | `required "aud" in jwt payload: ${JSON.stringify(payload)}` |
| `JwtTokenAudience` | `expected: string \| string[] \| RegExp, aud: string \| string[]` | `expected audience "${...}", got "${aud}"` |
Sources: [src/utils/jwt/types.ts:6-115](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/types.ts#L6-L115)
```typescript
export class JwtAlgorithmNotImplemented extends Error {
constructor(alg: string) {
super(`${alg} is not an implemented algorithm`)
this.name = 'JwtAlgorithmNotImplemented'
}
}
export class JwtAlgorithmRequired extends Error {
constructor() {
super('JWT verification requires "alg" option to be specified')
this.name = 'JwtAlgorithmRequired'
}
}
export class JwtAlgorithmMismatch extends Error {
constructor(expected: string, actual: string) {
super(`JWT algorithm mismatch: expected "${expected}", got "${actual}"`)
this.name = 'JwtAlgorithmMismatch'
}
}
export class JwtTokenInvalid extends Error {
constructor(token: string) {
super(`invalid JWT token: ${token}`)
this.name = 'JwtTokenInvalid'
}
}
export class JwtTokenNotBefore extends Error {
constructor(token: string) {
super(`token (${token}) is being used before it's valid`)
this.name = 'JwtTokenNotBefore'
}
}
export class JwtTokenExpired extends Error {
constructor(token: string) {
super(`token (${token}) expired`)
this.name = 'JwtTokenExpired'
}
}
export class JwtTokenIssuedAt extends Error {
constructor(currentTimestamp: number, iat: number) {
super(
`Invalid "iat" claim, must be a valid number lower than "${currentTimestamp}" (iat: "${iat}")`
)
this.name = 'JwtTokenIssuedAt'
}
}
export class JwtTokenIssuer extends Error {
constructor(expected: string | RegExp, iss: string | null) {
super(`expected issuer "${expected}", got ${iss ? `"${iss}"` : 'none'} `)
this.name = 'JwtTokenIssuer'
}
}
export class JwtHeaderInvalid extends Error {
constructor(header: object) {
super(`jwt header is invalid: ${JSON.stringify(header)}`)
this.name = 'JwtHeaderInvalid'
}
}
export class JwtHeaderRequiresKid extends Error {
constructor(header: object) {
super(`required "kid" in jwt header: ${JSON.stringify(header)}`)
this.name = 'JwtHeaderRequiresKid'
}
}
export class JwtSymmetricAlgorithmNotAllowed extends Error {
constructor(alg: string) {
super(`symmetric algorithm "${alg}" is not allowed for JWK verification`)
this.name = 'JwtSymmetricAlgorithmNotAllowed'
}
}
export class JwtAlgorithmNotAllowed extends Error {
```
Sources: [src/utils/jwt/types.ts:6-115](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/types.ts#L6-L115)
## Related
- [Basic and Bearer Auth](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/basic-and-bearer-auth)
- [Secure Headers and CORS](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/secure-headers-and-cors)
---
## Technical docs: Basic and Bearer Auth
URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/basic-and-bearer-auth
Relevant source files
The following files were used as context for generating this wiki page:
- [src/middleware/bearer-auth/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts)
- [src/utils/jwt/jwt.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts)
- [src/middleware/secure-headers/secure-headers.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts)
- [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts)
- [src/middleware/basic-auth/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts)
- [src/middleware/jwt/jwt.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts)
- [src/middleware/jwk/jwk.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/jwk.ts)
- [src/utils/basic-auth.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/basic-auth.ts)
- [src/middleware/jwk/keys.test.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/keys.test.json)
- [src/middleware/csrf/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts)
- [src/utils/jwt/jws.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts)
- [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts)
- [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts)
- [src/utils/headers.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/headers.ts)
- [src/utils/ipaddr.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts)
- [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts)
- [src/helper/proxy/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts)
- [src/utils/buffer.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts)
- [src/preset/quick.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts)
- [src/helper/streaming/text.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/text.ts)
- [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts)
- [src/middleware/etag/digest.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/digest.ts)
- [src/utils/jwt/utf8.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/utf8.ts)
- [src/utils/encode.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/encode.ts)
- [src/utils/cookie.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/cookie.ts)
- [src/utils/jwt/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/types.ts)
- [src/utils/accept.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts)
- [src/router/linear-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts)
- [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts)
- [src/middleware/jwt/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/index.ts)
## Overview
Hono provides built-in middleware for HTTP Basic and Bearer Auth to secure API endpoints by validating credentials against static configurations or custom verification handlers. These middlewares inspect incoming request headers, parse authorization schemes, and dispatch standardized HTTP exceptions with `401 Unauthorized` status codes and `WWW-Authenticate` challenge headers when verification fails.
Sources: [src/middleware/basic-auth/index.ts:31-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L31-L46), [src/middleware/bearer-auth/index.ts:88-89](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L88-L89)
To prevent timing side-channel attacks during credential comparison, the system utilizes constant-time string and buffer comparison algorithms implemented within utility modules.
Sources: [src/utils/buffer.ts:29-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L29-L63)
## Basic Authentication Flow
### Credential Matching Execution Walkthrough
The `basicAuth` middleware accepts an options object supporting either static username/password pairs or a custom `verifyUser` asynchronous callback function. The public configuration options also accept an optional `realm`, a `hashFunction` for credential normalization, an `invalidUserMessage` string, object, or message function, and an `onAuthSuccess` callback hook. If neither static credentials nor a `verifyUser` function are supplied, initialization throws an error.
Sources: [src/middleware/basic-auth/index.ts:14-30](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L14-L30), [src/middleware/basic-auth/index.ts:80-91](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L80-L91)
| Option Key | Type | Default Value | Description |
| :--- | :--- | :--- | :--- |
| `username` | `string` | — | Static username for authentication matching |
| `password` | `string` | — | Static password for authentication matching |
| `verifyUser` | `Function` | — | Custom verification handler taking `(username, password, c)` |
| `realm` | `string` | `"Secure Area"` | Realm attribute populated in the `WWW-Authenticate` header |
| `hashFunction` | `Function` | `sha256` | Hash function utilized during secure credential comparison |
| `invalidUserMessage` | `string \| object \| Function` | `"Unauthorized"` | Response body content returned on validation failure |
| `onAuthSuccess` | `Function` | — | Callback function invoked upon successful authentication |
Sources: [src/middleware/basic-auth/index.ts:36-43](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L36-L43), [src/middleware/basic-auth/index.ts:93-99](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L93-L99)
> [!NOTE]
> When static `username` and `password` properties are specified in the configuration object alongside rest parameters (`...users`), they are prepended to the internal user verification array via `users.unshift()`.
Sources: [src/middleware/basic-auth/index.ts:81-83](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L81-L83), [src/middleware/basic-auth/index.ts:101-103](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L101-L103)
When an incoming request is intercepted, the handler extracts and parses authorization credentials from the request headers using the basic auth utility function, checking the provided username and password against configured accounts or the custom verification handler via the execution chain: `basicAuth` → `timingSafeEqual` → `timingSafeEqualString` → `constantTimeEqualString`.
Sources: [src/middleware/basic-auth/index.ts:105-131](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L105-L131), [src/utils/buffer.ts:29-96](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L29-L96)
1. `basicAuth` invokes `auth(ctx.req.raw)` to extract the decoded request username and password, then iterates through configured users to invoke `timingSafeEqual(user.username, requestUser.username, options.hashFunction)` and `timingSafeEqual(user.password, requestUser.password, options.hashFunction)` via `Promise.all`.
Sources: [src/middleware/basic-auth/index.ts:106-121](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L106-L121)
2. `timingSafeEqual` checks argument types and routes string inputs to `timingSafeEqualString`.
Sources: [src/utils/buffer.ts:76-83](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L76-L83)
3. `timingSafeEqualString` resolves the active hash function (defaulting to `sha256`), computes hashed byte representations of both strings in parallel via `Promise.all`, and passes the resulting digests to `constantTimeEqualString`.
Sources: [src/utils/buffer.ts:44-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L44-L63)
4. `constantTimeEqualString` evaluates character codes across the maximum length utilizing bitwise operations to accumulate differences without early exits.
Sources: [src/utils/buffer.ts:29-40](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L29-L40)
```mermaid
sequenceDiagram
participant Index as src/middleware/basic-auth/index.ts
participant Buffer as src/utils/buffer.ts
Index->>Buffer: basicAuth() calls timingSafeEqual()
Buffer->>Buffer: timingSafeEqual() calls timingSafeEqualString()
Buffer->>Buffer: timingSafeEqualString() calls constantTimeEqualString()
```
Sources: [src/middleware/basic-auth/index.ts:118-121](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L118-L121), [src/utils/buffer.ts:76-83](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L76-L83), [src/utils/buffer.ts:44-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L44-L63), [src/utils/buffer.ts:29-40](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L29-L40)
## Parsing Authorization Credentials
### Credential Extraction and Decoding
The [Utilities and Encoding](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/utilities-and-encoding) page documents how low-level helpers manage character encoding [src/utils/encode.ts:1-4](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/encode.ts#L1-L4). Incoming HTTP requests are processed by the `auth` helper, which reads the `Authorization` header and matches it against `CREDENTIALS_REGEXP` to isolate the Base64-encoded payload portion [src/utils/basic-auth.ts:3-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/basic-auth.ts#L3-L10). If the header is missing or fails the regular expression pattern, the function immediately returns `undefined` [src/utils/basic-auth.ts:10-13](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/basic-auth.ts#L10-L13).
Sources: [src/utils/basic-auth.ts:3-13](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/basic-auth.ts#L3-L13), [src/utils/encode.ts:1-4](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/encode.ts#L1-L4)
### Execution Walkthrough and Sequence
1. `basicAuth` invokes `auth(ctx.req.raw)` to retrieve credentials from the raw request object [src/middleware/basic-auth/index.ts:106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L106).
Sources: [src/middleware/basic-auth/index.ts:106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L106)
2. `auth` executes `CREDENTIALS_REGEXP.exec` on the header string, captures group `1`, and passes it to `decodeBase64` [[src/utils/basic-auth.ts:10], [src/utils/basic-auth.ts:18]].
Sources: [src/utils/basic-auth.ts:10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/basic-auth.ts#L10], [src/utils/basic-auth.ts:18)
3. `decodeBase64` invokes `atob(str)` and constructs a `Uint8Array` using byte character codes [src/utils/encode.ts:25-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/encode.ts#L25-L33).
Sources: [src/utils/encode.ts:25-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/encode.ts#L25-L33)
```mermaid
sequenceDiagram
participant BasicAuth as src/middleware/basic-auth/index.ts
participant BasicAuthUtil as src/utils/basic-auth.ts
participant EncodeUtil as src/utils/encode.ts
BasicAuth->>BasicAuthUtil: auth(ctx.req.raw)
BasicAuthUtil->>EncodeUtil: decodeBase64(match[1])
EncodeUtil-->>BasicAuthUtil: Returns Uint8Array bytes
```
Sources: [src/middleware/basic-auth/index.ts:106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L106), [src/utils/basic-auth.ts:10-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/basic-auth.ts#L10-L18), [src/utils/encode.ts:25-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/encode.ts#L25-L33)
### Regular Expressions and Sanitization
| Constant Name | Regular Expression Pattern | Purpose |
| :--- | :--- | :--- |
| `CREDENTIALS_REGEXP` | `/^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/` | Matches and extracts the Base64 token following the Basic scheme prefix. |
| `USER_PASS_REGEXP` | `/^([^:]*):(.*)$/` | Splits the decoded string into username and password components across the first colon. |
Sources: [src/utils/basic-auth.ts:3-4](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/basic-auth.ts#L3-L4)
> [!WARNING]
> If an invalid string is passed to `atob()`, a `DOMException` is thrown; the `auth` function catches this exception inside a `try...catch` block and safely returns `undefined` rather than crashing the [request lifecycle](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/request-lifecycle).
Sources: [src/utils/basic-auth.ts:15-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/basic-auth.ts#L15-L20)
## Bearer Authentication Enforcement
### Bearer Options and Header Processing
The `bearerAuth` middleware requires options containing either a `token` (string or array of strings) or a `verifyToken` function. Optional configurations include `realm`, `prefix`, `headerName`, `hashFunction`, and customized error responses via `noAuthenticationHeader`, `invalidAuthenticationHeader`, and `invalidToken`. If neither `token` nor `verifyToken` is provided, the middleware throws an initialization error.
Sources: [src/middleware/bearer-auth/index.ts:22-50](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L22-L50), [src/middleware/bearer-auth/index.ts:107-109](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L107-L109)
| Option Name | Type | Default Value | Purpose |
| :--- | :--- | :--- | :--- |
| `token` | `string \| string[]` | `undefined` | The static token string or array of acceptable tokens. |
| `verifyToken` | `(token: string, c: Context) => boolean \| Promise` | `undefined` | Custom token verification callback function. |
| `realm` | `string` | `''` | Authentication realm string included in challenge headers. |
| `prefix` | `string` | `'Bearer'` | Expected scheme prefix preceding the token. |
| `headerName` | `string` | `'Authorization'` | Custom header name to inspect instead of `Authorization`. |
| `hashFunction` | `Function` | `sha256` | Custom hashing function used during token comparison. |
Sources: [src/middleware/bearer-auth/index.ts:22-50](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L22-L50), [src/middleware/bearer-auth/index.ts:110-115](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L110-L115), [src/utils/buffer.ts:50](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L50)
> [!NOTE]
> When `prefix` is set to an empty string `''`, scheme prefix validation is bypassed entirely, and the entire header value is treated directly as the token string.
Sources: [src/middleware/bearer-auth/index.ts:172-174](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L172-L174)
### Execution Walkthrough and Sequence
1. `bearerAuth` receives the request and inspects the specified HTTP header using `c.req.header(options.headerName || HEADER)`.
Sources: [src/middleware/bearer-auth/index.ts:156-157](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L156-L157)
2. If the header is missing, it dispatches an unauthorized exception via `throwHTTPException` with a 401 status.
Sources: [src/middleware/bearer-auth/index.ts:158-168](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L158-L168)
3. If present, it validates the scheme prefix case-insensitively, trims leading whitespace, and tests the extracted token against `tokenRegexp` (`^[A-Za-z0-9._~+/-]+=*$`).
Sources: [src/middleware/bearer-auth/index.ts:12-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L12-L19), [src/middleware/bearer-auth/index.ts:175-182](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L175-L182)
4. If token validation fails, a 400 Bad Request exception is thrown.
Sources: [src/middleware/bearer-auth/index.ts:182-192](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L182-L192)
5. Otherwise, credential matching delegates to `verifyToken` or calls `timingSafeEqual`.
Sources: [src/middleware/bearer-auth/index.ts:195-206](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L195-L206)
6. `timingSafeEqual` invokes `timingSafeEqualString`.
Sources: [src/utils/buffer.ts:76-83](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L76-L83)
7. `timingSafeEqualString` invokes `constantTimeEqualString` for byte and hash verification.
Sources: [src/utils/buffer.ts:44-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L44-L63)
```mermaid
sequenceDiagram
participant BearerAuth as src/middleware/bearer-auth/index.ts
participant BufferUtil as src/utils/buffer.ts
BearerAuth->>BufferUtil: timingSafeEqual(options.token, tokenValue, options.hashFunction)
BufferUtil->>BufferUtil: timingSafeEqualString(a, b, hashFunction)
BufferUtil->>BufferUtil: constantTimeEqualString(sa, sb)
```
Sources: [src/middleware/bearer-auth/index.ts:198](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L198), [src/utils/buffer.ts:76-83](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L76-L83), [src/utils/buffer.ts:44-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L44-L63), [src/utils/buffer.ts:29-40](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L29-L40)
## Timing-Attack Mitigation
### Constant-Time Comparison Operations
Hono implements timing-attack mitigation utilities in `src/utils/buffer.ts` to prevent attackers from inferring secret tokens or passwords via response latency side channels. The lowest-level primitive, `constantTimeEqualString`, processes two strings character by character without short-circuiting on mismatch:
```typescript
const constantTimeEqualString = (a: string, b: string): boolean => {
const aLen = a.length
const bLen = b.length
const maxLen = Math.max(aLen, bLen)
let out = aLen ^ bLen
for (let i = 0; i < maxLen; i++) {
const aChar = i < aLen ? a.charCodeAt(i) : 0
const bChar = i < bLen ? b.charCodeAt(i) : 0
out |= aChar ^ bChar
}
return out === 0
}
```
Sources: [src/utils/buffer.ts:29-40](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L29-L40)
> [!CAUTION]
> Length differences between strings are accumulated into the XOR accumulator via `aLen ^ bLen`, preventing length-extension leaks from exiting early when string lengths diverge.
Sources: [src/utils/buffer.ts:33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L33)
### ArrayBuffer and String Equivalence
Higher-level comparison functions handle binary `ArrayBuffer` instances as well as hashed and unhashed strings. The `equal` function compares two `ArrayBuffer` instances using a DataView iteration loop:
```typescript
export const equal = (a: ArrayBuffer, b: ArrayBuffer): boolean => {
if (a === b) {
return true
}
if (a.byteLength !== b.byteLength) {
return false
}
const va = new DataView(a)
const vb = new DataView(b)
let i = va.byteLength
while (i--) {
if (va.getUint8(i) !== vb.getUint8(i)) {
return false
}
}
return true
}
```
Sources: [src/utils/buffer.ts:8-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L8-L27)
The `timingSafeEqualString` function wraps string hashing and comparison. By default, if no custom `hashFunction` is provided, it falls back to `sha256`:
```typescript
const timingSafeEqualString = async (
a: string,
b: string,
hashFunction?: StringHashFunction
): Promise => {
if (!hashFunction) {
hashFunction = sha256
}
const [sa, sb] = await Promise.all([hashFunction(a), hashFunction(b)])
if (sa == null || sb == null || typeof sa !== 'string' || typeof sb !== 'string') {
return false
}
const hashEqual = constantTimeEqualString(sa, sb)
const originalEqual = constantTimeEqualString(a, b)
return hashEqual && originalEqual
}
```
Sources: [src/utils/buffer.ts:44-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L44-L63)
> [!NOTE]
> `timingSafeEqualString` evaluates both `constantTimeEqualString(sa, sb)` on the hashed outputs and `constantTimeEqualString(a, b)` on the raw inputs concurrently, returning true only if both comparisons succeed.
Sources: [src/utils/buffer.ts:53-62](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L53-L62)
The exported `timingSafeEqual` entry point normalizes inputs and routes execution depending on whether parameters are strings or generic objects/booleans:
```typescript
export const timingSafeEqual: TimingSafeEqual = async (
a,
b,
hashFunction?: Function
): Promise => {
if (typeof a === 'string' && typeof b === 'string') {
return timingSafeEqualString(a, b, hashFunction as StringHashFunction)
}
if (!hashFunction) {
hashFunction = sha256
}
const [sa, sb] = await Promise.all([hashFunction(a), hashFunction(b)])
if (!sa || !sb || typeof sa !== 'string' || typeof sb !== 'string') {
return false
}
return timingSafeEqualString(sa, sb)
}
```
Sources: [src/utils/buffer.ts:76-96](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L76-L96)
## Authentication Challenges and Error Dispatch
### HTTPException Instantiation and Response Generation
When authentication fails across Hono's authentication middlewares, error handling is dispatched via `HTTPException` combined with custom `Response` instances. The `basicAuth` middleware evaluates the parsed user credentials against configured options or user lists. Upon failure, it constructs a 401 Unauthorized status response containing the `WWW-Authenticate` header populated with the escaped realm name. If `invalidUserMessage` is configured as a function or an object, it is dynamically serialized into a text or JSON payload before throwing the `HTTPException`:
```typescript
// Invalid user.
const status = 401
const headers = {
'WWW-Authenticate': 'Basic realm="' + options.realm?.replace(/"/g, '\\"') + '"',
}
const responseMessage =
typeof options.invalidUserMessage === 'function'
? await options.invalidUserMessage(ctx)
: options.invalidUserMessage
const res =
typeof responseMessage === 'string'
? new Response(responseMessage, { status, headers })
: new Response(JSON.stringify(responseMessage), {
status,
headers: {
...headers,
'content-type': 'application/json',
},
})
throw new HTTPException(status, { res })
}
```
Sources: [src/middleware/basic-auth/index.ts:132-152](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L132-L152)
Similarly, the `bearerAuth` middleware defines a private `throwHTTPException` helper function to encapsulate status codes, challenge headers, and message body construction. Depending on the specific failure branch—such as missing headers, malformed requests, or invalid tokens—it issues status codes 401, 400, or 401 respectively.
Sources: [src/middleware/bearer-auth/index.ts:122-154](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L122-L154)
> [!WARNING]
> Realms containing double quotes are automatically escaped via `options.realm?.replace(/"/g, '\\"')` prior to header injection to prevent header injection vulnerabilities.
Sources: [src/middleware/basic-auth/index.ts:135](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L135), [src/middleware/bearer-auth/index.ts:117](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L117)
### WWW-Authenticate Challenge Construction
The construction of challenge headers differs between schemes based on whether options specify plain strings, objects, or callback functions. The `bearerAuth` middleware processes `wwwAuthenticateHeader` parameters by checking their type. If an object is supplied, its entries are mapped into comma-separated key-value pairs appended to the challenge prefix:
```typescript
const wwwAuthenticateHeaderValue: string | object =
typeof wwwAuthenticateHeader === 'function'
? await wwwAuthenticateHeader(c)
: wwwAuthenticateHeader
const headers = {
'WWW-Authenticate':
typeof wwwAuthenticateHeaderValue === 'string'
? wwwAuthenticateHeaderValue
: `${wwwAuthenticatePrefix}${Object.entries(wwwAuthenticateHeaderValue)
.map(([key, value]) => `${key}="${value}"`)
.join(',')}`,
}
```
Sources: [src/middleware/bearer-auth/index.ts:128-140](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L128-L140)
For JSON Web Token workflows in `jwt` and `jwk` middlewares, failed verifications or missing tokens trigger `unauthorizedResponse`, which formats challenge headers including the current request URL, error codes, and detailed descriptions:
```typescript
function unauthorizedResponse(opts: {
ctx: Context
error: string
errDescription: string
statusText?: string
}) {
return new Response('Unauthorized', {
status: 401,
statusText: opts.statusText,
headers: {
'WWW-Authenticate': `Bearer realm="${opts.ctx.req.url}",error="${opts.error}",error_description="${opts.errDescription}"`,
},
})
}
```
Sources: [src/middleware/jwt/jwt.ts:160-173](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L160-L173), [src/middleware/jwk/jwk.ts:170-182](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/jwk.ts#L170-L182)
| Middleware | Default Status Code | Default WWW-Authenticate Challenge | Message Payload Handling |
| :--- | :--- | :--- | :--- |
| `basicAuth` | `401` | `Basic realm="..."` | Text or JSON via `invalidUserMessage` |
| `bearerAuth` (Missing) | `401` | `Bearer realm="..."` | Text or JSON via `noAuthenticationHeader.message` |
| `bearerAuth` (Invalid Request) | `400` | `Bearer error="invalid_request"` | Text or JSON via `invalidAuthenticationHeader.message` |
| `bearerAuth` (Invalid Token) | `401` | `Bearer error="invalid_token"` | Text or JSON via `invalidToken.message` |
| `jwt` / `jwk` | `401` | `Bearer realm="...",error="...",error_description="..."` | Static string `'Unauthorized'` |
Sources: [src/middleware/basic-auth/index.ts:133-151](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L133-L151), [src/middleware/bearer-auth/index.ts:160-215](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L160-L215), [src/middleware/jwt/jwt.ts:160-173](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L160-L173), [src/middleware/jwk/jwk.ts:170-182](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/jwk.ts#L170-L182)
## Related
- [JWT and JWK](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/jwt-and-jwk)
---
## Technical docs: Secure Headers and CORS
URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/secure-headers-and-cors