---
title: "Middleware Composition"
description: "Middleware composition in Hono orchestrates request processing pipelines through recursive dispatching and onion-model execution src/compose.ts:15-72. By combining middleware functions, conditional..."
last_updated: "2026-10-12T08:14:12.710392+00:00"
canonical_url: "https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/core-engine/middleware-composition"
---


## Overview

Middleware composition in Hono orchestrates request processing pipelines through recursive dispatching and onion-model execution src/compose.ts:15-72. 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, src/middleware/combine/index.ts:38-164, src/helper/factory/index.ts:353-360.


## 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. 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/core-engine/execution-context) instance src/compose.ts:15-19.

```typescript
export const compose = <E extends Env = Env>(
  middleware: [[Function, unknown], unknown][] | [[Function]][],
  onError?: ErrorHandler<E>,
  onNotFound?: NotFoundHandler<E>
): ((context: Context, next?: Next) => Promise<Context>) => {
  return (context, next) => {
    let index = -1

    return dispatch(0)

```

Each invocation tracks index advancement through the `index` local variable src/compose.ts:21-36. 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. This guard prevents middleware from calling `next()` multiple times within the same execution cycle src/compose.ts:33-35.

> [!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.


### 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. 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.

```typescript
if (middleware[i]) {
  handler = middleware[i][0][0]
  context.req.routeIndex = i
} else {
  handler = (i === middleware.length && next) || undefined
}

```

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. 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. If no `onError` handler is present, the error is rethrown src/compose.ts:57-59.

```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)
  }
}
```

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. 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.


## 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. These functions inspect the Execution Context or intercept continuation calls to conditionally bypass or enforce middleware execution src/middleware/combine/index.ts:38-165.

```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
    }
  }
}
```

The `some` helper iterates over an array of middleware or condition functions sequentially src/middleware/combine/index.ts:38-47. 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. If a handler returns `false`, it records a new `Error('No successful middleware found')` and continues src/middleware/combine/index.ts:52-55.

```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)
  }
}
```

The `every` helper wraps all provided middleware items inside a `compose` pipeline src/middleware/combine/index.ts:99-115. 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.

> [!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.


### 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. String patterns are added to a private `TrieRouter<true>` instance using `METHOD_NAME_ALL`, while condition functions are collected directly into an evaluation array src/middleware/combine/index.ts:145-155. 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.

```typescript
export const except = (
  condition: string | Condition | (string | Condition)[],
  ...middleware: MiddlewareHandler[]
): MiddlewareHandler => {
  let router: TrieRouter<true> | 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)
  }
}
```

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.

1. `except` evaluates path conditions and constructs a composite handler via `some` and `every` src/middleware/combine/index.ts:161-162.
2. `handler` executes the `some` wrapper logic to test whether the exclusion condition matches the context src/middleware/combine/index.ts:39-68.
3. `every` maps the remaining middleware array into individual wrapped handlers that enforce boolean checks src/middleware/combine/index.ts:102-114.
4. `compose` aggregates the mapped middleware items into a linear execution array src/compose.ts:15-19.
5. `dispatch` recursively steps through index `i` to execute each middleware layer in the onion pipeline src/compose.ts:32-71.

```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
```


## 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.

```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
    }
  }
}
```

Incoming requests flow through a specific sequence of internal functions during short-circuiting operations src/middleware/combine/index.ts:38-164.

1. `except` evaluates route path patterns and custom predicates src/middleware/combine/index.ts:141-164.
2. `handler` invokes the composed `some` wrapper src/middleware/combine/index.ts:161-163.
3. `some` iterates over its middleware arguments, calling each with `c` and `wrappedNext` src/middleware/combine/index.ts:47-49.
4. `wrappedNext` sets `isPreserved` flags or `isNextCalled` to `true` before triggering downstream execution src/middleware/combine/index.ts:41-44.

```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()
```


> [!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.


## 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. 

```typescript
export class Factory<E extends Env = Env, P extends string = string> {
  private initApp?: InitApp<E>
  #defaultAppOptions?: HonoOptions<E>

  constructor(init?: { initApp?: InitApp<E>; defaultAppOptions?: HonoOptions<E> }) {
    this.initApp = init?.initApp
    this.#defaultAppOptions = init?.defaultAppOptions
  }

  createApp = (options?: HonoOptions<E>): Hono<E> => {
    const app = new Hono<E>(
      options && this.#defaultAppOptions
        ? { ...this.#defaultAppOptions, ...options }
        : (options ?? this.#defaultAppOptions)
    )
    if (this.initApp) {
      this.initApp(app)
    }
    return app
  }
```

> [!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.


### 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. Type parameters use `IntersectNonAnyTypes` to accumulate context extensions without polluting the base types src/helper/factory/index.ts:88-92.

| 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<any>` | Return type validation for individual middleware steps |
| `P` | `string` | URL parameter matching string constraint |


## 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. The `isMiddleware` helper checks whether a handler function expects multiple parameters, corresponding to the `(c, next)` middleware signature src/utils/handler.ts:8. 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.

```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
```

> [!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.


## Related

- [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/core-engine/application-core)
- [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/core-engine/execution-context)


## Sitemap

See the full [sitemap](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/llms.txt) for all pages in this wiki.
