Hono’s middleware system is flexible and can integrate with third-party packages. This guide covers how to use external middleware and lists popular options.
Middleware Compatibility
Hono middleware follows a simple signature:
import type { MiddlewareHandler } from 'hono'
const middleware : MiddlewareHandler = async ( c , next ) => {
// Middleware logic
await next ()
}
Any function matching this signature can be used as Hono middleware, whether it comes from a third-party package or is written inline.
Using Third-Party Middleware
Direct Compatible Middleware
If a package exports Hono-compatible middleware, you can use it directly:
import { Hono } from 'hono'
import { someMiddleware } from 'third-party-hono-middleware'
const app = new Hono ()
app . use ( someMiddleware ({
option1: 'value1' ,
option2: 'value2'
}))
app . get ( '/' , ( c ) => c . text ( 'Hello!' ))
Wrapping Express/Connect Middleware
While Hono and Express have different middleware signatures, you can create adapters:
import { Hono } from 'hono'
import type { MiddlewareHandler } from 'hono'
// Example Express-style middleware
function expressMiddleware ( req : any , res : any , next : any ) {
// Express middleware logic
next ()
}
// Adapter function
function expressToHono ( expressMiddleware : Function ) : MiddlewareHandler {
return async ( c , next ) => {
// This is a simplified example
// Real implementation would need more conversion
await new Promise (( resolve ) => {
expressMiddleware (
c . req . raw ,
c . res ,
resolve
)
})
await next ()
}
}
const app = new Hono ()
app . use ( expressToHono ( expressMiddleware ))
Note that Express middleware may not always work perfectly with Hono due to different runtime environments and API differences. Test thoroughly when adapting middleware.
Popular Third-Party Middleware
Authentication & Authorization
@hono/auth-js Auth.js (NextAuth.js) integration for Hono npm install @hono/auth-js
import { Hono } from 'hono'
import { authHandler } from '@hono/auth-js'
const app = new Hono ()
app . use ( '/auth/*' , authHandler ())
@hono/oauth-providers OAuth provider integrations npm install @hono/oauth-providers
import { googleAuth } from '@hono/oauth-providers/google'
app . use ( '/auth/google' , googleAuth ({
client_id: process . env . GOOGLE_CLIENT_ID ,
client_secret: process . env . GOOGLE_CLIENT_SECRET
}))
Validation & Parsing
@hono/zod-validator Validate requests using Zod schemas npm install @hono/zod-validator zod
import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'
const schema = z . object ({
name: z . string (),
age: z . number ()
})
app . post ( '/user' , zValidator ( 'json' , schema ), ( c ) => {
const data = c . req . valid ( 'json' )
return c . json ({ success: true , data })
})
@hono/valibot-validator Validate requests using Valibot npm install @hono/valibot-validator valibot
import { vValidator } from '@hono/valibot-validator'
import * as v from 'valibot'
const schema = v . object ({
name: v . string (),
age: v . number ()
})
app . post ( '/user' , vValidator ( 'json' , schema ), ( c ) => {
const data = c . req . valid ( 'json' )
return c . json ({ success: true })
})
Observability & Monitoring
@hono/sentry Sentry error tracking integration npm install @hono/sentry @sentry/node
import { sentry } from '@hono/sentry'
app . use ( sentry ({
dsn: process . env . SENTRY_DSN
}))
@hono/prometheus Prometheus metrics collection npm install @hono/prometheus
import { prometheus } from '@hono/prometheus'
const { printMetrics , registerMetrics } = prometheus ()
app . use ( '*' , registerMetrics )
app . get ( '/metrics' , printMetrics )
Database & ORM
@hono/prisma Prisma ORM integration npm install @hono/prisma @prisma/client
import { Hono } from 'hono'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient ()
const app = new Hono <{
Variables : { prisma : PrismaClient }
}>()
app . use ( '*' , async ( c , next ) => {
c . set ( 'prisma' , prisma )
await next ()
})
@hono/graphql-server GraphQL server middleware npm install @hono/graphql-server graphql
import { graphqlServer } from '@hono/graphql-server'
app . use ( '/graphql' , graphqlServer ({
schema: yourSchema
}))
Template Engines
@hono/react-renderer Server-side React rendering npm install @hono/react-renderer react react-dom
import { reactRenderer } from '@hono/react-renderer'
app . use ( reactRenderer ())
app . get ( '/' , ( c ) => {
return c . render (< h1 > Hello from React !</ h1 > )
})
@hono/ejs-renderer EJS template rendering npm install @hono/ejs ejs
import { ejs } from '@hono/ejs'
app . use ( '/views/*' , ejs ())
app . get ( '/views/page' , ( c ) => {
return c . render ( 'template.ejs' , { title: 'Hello' })
})
Utilities
@hono/swagger Swagger/OpenAPI documentation npm install @hono/swagger
import { swaggerUI } from '@hono/swagger'
app . get ( '/docs' , swaggerUI ({ url: '/openapi.json' }))
@hono/firebase-auth Firebase Authentication middleware npm install @hono/firebase-auth firebase-admin
import { firebaseAuth } from '@hono/firebase-auth'
app . use ( '/api/*' , firebaseAuth ())
Creating Middleware Packages
If you’re creating a middleware package for others to use:
Package Structure
// src/index.ts
import type { MiddlewareHandler } from 'hono'
export interface MyMiddlewareOptions {
option1 : string
option2 ?: number
}
export const myMiddleware = ( options : MyMiddlewareOptions ) : MiddlewareHandler => {
return async ( c , next ) => {
// Your middleware logic here
console . log ( 'Option 1:' , options . option1 )
await next ()
}
}
Package.json Setup
{
"name" : "hono-my-middleware" ,
"version" : "1.0.0" ,
"main" : "./dist/index.js" ,
"types" : "./dist/index.d.ts" ,
"exports" : {
"." : {
"import" : "./dist/index.js" ,
"types" : "./dist/index.d.ts"
}
},
"peerDependencies" : {
"hono" : "^4.0.0"
},
"keywords" : [
"hono" ,
"middleware" ,
"hono-middleware"
]
}
Documentation Example
# hono-my-middleware
A middleware for Hono that does X.
## Installation
```bash
npm install hono-my-middleware
Usage
import { Hono } from 'hono'
import { myMiddleware } from 'hono-my-middleware'
const app = new Hono ()
app . use ( myMiddleware ({
option1: 'value'
}))
Options
option1 (required): Description
option2 (optional): Description
### Testing Your Middleware
```typescript
import { Hono } from 'hono'
import { describe, it, expect } from 'vitest'
import { myMiddleware } from './index'
describe('myMiddleware', () => {
it('should work correctly', async () => {
const app = new Hono()
app.use(myMiddleware({ option1: 'test' }))
app.get('/test', (c) => c.text('OK'))
const res = await app.request('/test')
expect(res.status).toBe(200)
})
})
Finding Middleware
Discover Hono middleware packages:
Official Middleware Browse the official Hono middleware repository
npm Search Search npm for packages tagged with hono-middleware
Best Practices
Before using third-party middleware, verify:
It’s compatible with your Hono version
It works with your runtime (Cloudflare Workers, Deno, Bun, Node.js)
It’s actively maintained
It has good documentation
Always test third-party middleware in a development environment before deploying to production: import { describe , it } from 'vitest'
describe ( 'Third-party middleware integration' , () => {
it ( 'should work with my app' , async () => {
// Test the middleware with your app
})
})
Wrap third-party middleware in error handlers: import { Hono } from 'hono'
import type { MiddlewareHandler } from 'hono'
import { thirdPartyMiddleware } from 'some-package'
const safeMiddleware : MiddlewareHandler = async ( c , next ) => {
try {
await thirdPartyMiddleware ()( c , next )
} catch ( error ) {
console . error ( 'Middleware error:' , error )
return c . json ({ error: 'Middleware failed' }, 500 )
}
}
const app = new Hono ()
app . use ( safeMiddleware )
Keep dependencies updated
Regularly update middleware packages to get:
Security fixes
Performance improvements
New features
Bug fixes
Contributing
If you create a useful middleware, consider:
Open sourcing it - Share it with the community on GitHub
Publishing to npm - Make it easy for others to install
Tagging properly - Use the hono-middleware keyword
Documenting well - Include examples and API documentation
Adding tests - Ensure it works correctly
Submitting to awesome-hono - Get it listed in community resources
Built-in Middleware Explore Hono’s built-in middleware
Custom Middleware Learn to create your own middleware