Skip to main content
doc0blade47/honodocumentation home
Sign in

Middleware Composition

Last updated Oct 12, 2026
Relevant source files

The following files were used as context for generating this wiki page:

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.

Sources: src/compose.ts:15-72, src/middleware/combine/index.ts:38-164, src/helper/factory/index.ts:353-360, src/types.ts:305-347, src/utils/handler.ts:8-14

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 instance src/compose.ts:15-19.

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)
 

Sources: src/compose.ts:15-24

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.

Sources: src/compose.ts:33-35

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.

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

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.

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

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.

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

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

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.

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

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.

Sources: src/middleware/combine/index.ts:101-106

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.

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

Sources: src/middleware/combine/index.ts:141-165

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.

Sources: src/compose.ts:15-71, src/middleware/combine/index.ts:39-164

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.

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

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.

Sources: src/middleware/combine/index.ts:38-164

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.

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

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
  }

Sources: src/helper/factory/index.ts:332-351

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.

Sources: 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 ParameterBase Type / ConstraintPurpose
E / E2–E11EnvEnvironment binding accumulation across chained handlers
I / I2–I10InputRequest input validation types and schema intersections
R / R2–R10HandlerResponse<any>Return type validation for individual middleware steps
PstringURL parameter matching string constraint

Sources: src/helper/factory/index.ts:77-329

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.

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

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.

Sources: src/utils/handler.ts:8

Was this page helpful?