Skip to main content

What is Middleware?

Middleware is a function that runs before your route handler. It can modify the request, response, or perform side effects like logging, authentication, or error handling. Middleware functions have access to the context object and a next() function to pass control to the next middleware or route handler.

Middleware Execution Flow

Middleware executes in the order it’s registered:
This “onion model” allows middleware to execute code both before and after the route handler.

Using Middleware with app.use()

The app.use() method registers middleware. It can be used in several ways:

Global Middleware

Apply middleware to all routes:

Route-Specific Middleware

Apply middleware to specific routes or paths:

Multiple Middleware

Chain multiple middleware together:

Middleware Ordering

Middleware order matters! They execute in the order they’re registered:
Global middleware (using * or no path) should typically be registered first, followed by more specific path-based middleware.

Middleware Pattern Matching

Path patterns determine when middleware executes:

Built-in vs Custom vs Third-Party

Hono provides three types of middleware:

Built-in Middleware

Shipped with Hono and ready to use:

Custom Middleware

Create your own middleware for specific needs:

Third-Party Middleware

Middleware from the community or other compatible libraries:

Next Steps

Built-in Middleware

Explore all built-in middleware that ships with Hono

Custom Middleware

Learn how to create your own middleware

Third-Party Middleware

Integrate external middleware packages