Skip to main content
Custom middleware allows you to extend Hono with your own functionality. This guide shows you how to create middleware for various use cases.

Basic Middleware Structure

A middleware is a function that receives the context object and a next() function:

The Context Object

The context object (c) provides access to the request and response:

Calling next()

The next() function passes control to the next middleware or route handler. Always await it:
Always await next() to ensure proper middleware execution order and error handling.

Common Middleware Patterns

Before/After Pattern

Execute code before and after the route handler:

Early Return Pattern

Return a response without calling next():

Modifying Request Data

Add data to the context for later use:

Modifying Response

Change the response after the handler:

Parameterized Middleware

Create middleware that accepts options:

Error Handling

Handle errors in middleware:

Async Operations

Perform async operations in middleware:

TypeScript Types

Properly type your middleware for better type safety:

Factory Pattern

Create a reusable middleware factory:

Testing Middleware

Test your custom middleware:

Best Practices

Failing to await next() can cause unexpected behavior and broken error handling:
Use c.set() to store values instead of adding properties:
Wrap risky operations in try-catch blocks:
Define your environment types for better IDE support:
Each middleware should have a single, clear responsibility:

Built-in Middleware

Explore built-in middleware for reference

Third-Party Middleware

Learn about external middleware packages