Skip to main content

Overview

Middleware are functions that execute during the request-response cycle. They have access to the Context object and can modify the request, response, or pass control to the next middleware.

What is Middleware?

Middleware functions are handlers that:
  • Execute before the final route handler
  • Can perform operations like authentication, logging, or validation
  • Can modify the request or response
  • Must call next() to pass control to the next handler
  • Can short-circuit the chain by returning a response
From src/types.ts:83-88:

Using Middleware

Global Middleware

Apply middleware to all routes:

Path-Specific Middleware

Apply middleware to specific paths:

Inline Middleware

Use middleware for specific routes:

The Next Function

The next function passes control to the next middleware or handler in the chain. From src/types.ts:35:

Calling Next

Always await the next() call. Without await, the middleware will continue executing before the handler completes, which can lead to unexpected behavior.

Multiple Calls to Next

Calling next() multiple times throws an error:
From src/compose.ts:33-35:

Middleware Execution Order

Middleware executes in the order it is defined, following the compose pattern from koa-compose. From src/compose.ts:4-73:

Example: Execution Flow

Creating Custom Middleware

Basic Middleware

Middleware with Configuration

Type-Safe Middleware

Built-in Middleware

Hono provides many built-in middleware for common tasks:

Middleware Registration

From src/hono-base.ts:156-168:
The use method:
  • Accepts a path (optional) and one or more handlers
  • Defaults to '*' if no path is provided
  • Registers middleware for all HTTP methods

Short-Circuiting

Middleware can return a response to short-circuit the chain:

Error Handling in Middleware

Errors thrown in middleware are caught and passed to the error handler:
From src/compose.ts:50-60, errors are caught during dispatch:

Modifying the Response

Middleware can modify the response after the handler executes:

Best Practices

  • Always await next() unless intentionally short-circuiting
  • Register global middleware before route definitions
  • Use specific paths for middleware when possible for better performance
  • Keep middleware focused on a single responsibility
  • Use TypeScript to ensure type safety for context variables
Avoid calling next() multiple times in the same middleware. This will throw an error and stop execution.
  • Handlers - Learn about request handlers
  • Context - Access request and response data
  • Validation - Validate request data with middleware