Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
Middleware is a function that runs during the request–response cycle—before a request is handled or before a response is sent.
Hono includes built-in middleware, and you can add your own or use community middleware. Below are a few examples of what middleware can do.
Logger
Example: a logger.
import { logger } from 'hono/logger'
//...
app.use('*', logger())
This logs all server activity to the console:

Basic authentication
Restrict routes with HTTP basic auth:
import { basicAuth } from 'hono/basic-auth'
//...
app.use('/dashboard', basicAuth({
username: 'test',
password: 'test'
}))
app.get('/dashboard', (c) => {
return c.text('Logged in')
})

The route is accessible only with the correct credentials; otherwise the client gets 401 Unauthorized.

Implement CORS
import { cors } from 'hono/cors'
//...
app.use('/api/*', cors())
(You can use many options)
Set cache headers
import { cache } from 'hono/cache'
//...
app.get(
'*',
cache({
cacheName: 'my-app',
cacheControl: 'max-age=3600',
})
)
Set compression headers
import { compress } from 'hono/compress'
//...
app.use('*', compress())
For more middleware, see the official documentation.
Lessons in this unit:
| 0: | Introduction |
| 1: | Your first Hono app |
| 2: | The Request object |
| 3: | Send a response to the client |
| 4: | Manage cookies |
| 5: | Work with HTTP headers |
| 6: | Handling redirects |
| 7: | Routing |
| 8: | JSX templates |
| 9: | ▶︎ Middleware |
| 10: | Hono on Node.js |