On this page
Introduction
Onion structure
The important concepts of Hono are ”handler” and “middleware”.
A handler is a place to write a function that receives a request and returns a response, as specified by the user. For example, you can write a handler that gets a value of a query parameter, retrieves data from a database, and returns the result in JSON. Middleware can handle the requests that come to the handler and the responses that the handler returns. You can combine middleware with other middleware to build more large and complex applications. It is structured like an onion.

In a remarkably simple way, you can create middleware.
For example, a custom logger that logs the request can be written as follows:
app.use(async (c, next) => { console.log(`[${c.req.method}] ${c.req.path}`) await next()})If you want to add a custom header to the response, write the following:
app.use(async (c, next) => { await next() c.header('X-Message', 'Hi, this is Hono!')})It would be interesting to combine this with HTMLRewriter. If an endpoint returns HTML, the middleware that modifies the HTML tags in it can be written as follows:
app.get('/pages/*', async (c, next) => { await next()
class AttributeRewriter { constructor(attributeName) { this.attributeName = attributeName } element(element) { const attribute = element.getAttribute(this.attributeName) if (attribute) { element.setAttribute(this.attributeName, attribute.replace('oldhost', 'newhost')) } } } const rewriter = new HTMLRewriter().on('a', new AttributeRewriter('href'))
const contentType = c.res.headers.get('Content-Type')
if (contentType!.startsWith('text/html')) { c.res = rewriter.transform(c.res) }})There is very little to remember to create middleware. All you have to do is to work with the context, which you should already know.