Creating Middleware in Hono

From the Hono cheat sheet · Middleware · verified Jul 2026

Creating Middleware

Define and use custom middleware

typescript
// Basic middleware
app.use('*', async (c, next) => {
  console.log('Before handler')
  await next()
  console.log('After handler')
})

// Path-specific middleware
app.use('/api/*', async (c, next) => {
  const start = Date.now()
  await next()
  const ms = Date.now() - start
  c.header('X-Response-Time', \`\${ms}ms\`)
})

// Using createMiddleware for type safety
import { createMiddleware } from 'hono/factory'

const authMiddleware = createMiddleware(async (c, next) => {
  const token = c.req.header('Authorization')
  if (!token) {
    return c.json({ error: 'Unauthorized' }, 401)
  }
  await next()
})
💡 Always call await next() to continue the chain
⚡ Middleware runs before handler, after next() returns
📌 Use createMiddleware from "hono/factory" for types
🎯 Return a response to short-circuit the chain

More Hono tasks

Back to the full Hono cheat sheet