> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/honojs/hono/llms.txt
> Use this file to discover all available pages before exploring further.

# Third-Party Middleware

> Using external middleware packages with Hono

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:

```typescript theme={null}
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:

```typescript theme={null}
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:

```typescript theme={null}
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))
```

<Warning>
  Note that Express middleware may not always work perfectly with Hono due to different runtime environments and API differences. Test thoroughly when adapting middleware.
</Warning>

## Popular Third-Party Middleware

### Authentication & Authorization

<CardGroup cols={2}>
  <Card title="@hono/auth-js" icon="shield" href="https://github.com/honojs/middleware/tree/main/packages/auth-js">
    Auth.js (NextAuth.js) integration for Hono

    ```bash theme={null}
    npm install @hono/auth-js
    ```

    ```typescript theme={null}
    import { Hono } from 'hono'
    import { authHandler } from '@hono/auth-js'

    const app = new Hono()
    app.use('/auth/*', authHandler())
    ```
  </Card>

  <Card title="@hono/oauth-providers" icon="key" href="https://github.com/honojs/middleware/tree/main/packages/oauth-providers">
    OAuth provider integrations

    ```bash theme={null}
    npm install @hono/oauth-providers
    ```

    ```typescript theme={null}
    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
    }))
    ```
  </Card>
</CardGroup>

### Validation & Parsing

<CardGroup cols={2}>
  <Card title="@hono/zod-validator" icon="check-circle" href="https://github.com/honojs/middleware/tree/main/packages/zod-validator">
    Validate requests using Zod schemas

    ```bash theme={null}
    npm install @hono/zod-validator zod
    ```

    ```typescript theme={null}
    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 })
    })
    ```
  </Card>

  <Card title="@hono/valibot-validator" icon="shield-check" href="https://github.com/honojs/middleware/tree/main/packages/valibot-validator">
    Validate requests using Valibot

    ```bash theme={null}
    npm install @hono/valibot-validator valibot
    ```

    ```typescript theme={null}
    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 })
    })
    ```
  </Card>
</CardGroup>

### Observability & Monitoring

<CardGroup cols={2}>
  <Card title="@hono/sentry" icon="bug" href="https://github.com/honojs/middleware/tree/main/packages/sentry">
    Sentry error tracking integration

    ```bash theme={null}
    npm install @hono/sentry @sentry/node
    ```

    ```typescript theme={null}
    import { sentry } from '@hono/sentry'

    app.use(sentry({
      dsn: process.env.SENTRY_DSN
    }))
    ```
  </Card>

  <Card title="@hono/prometheus" icon="chart-line" href="https://github.com/honojs/middleware/tree/main/packages/prometheus">
    Prometheus metrics collection

    ```bash theme={null}
    npm install @hono/prometheus
    ```

    ```typescript theme={null}
    import { prometheus } from '@hono/prometheus'

    const { printMetrics, registerMetrics } = prometheus()

    app.use('*', registerMetrics)
    app.get('/metrics', printMetrics)
    ```
  </Card>
</CardGroup>

### Database & ORM

<CardGroup cols={2}>
  <Card title="@hono/prisma" icon="database" href="https://github.com/honojs/middleware/tree/main/packages/prisma">
    Prisma ORM integration

    ```bash theme={null}
    npm install @hono/prisma @prisma/client
    ```

    ```typescript theme={null}
    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()
    })
    ```
  </Card>

  <Card title="@hono/graphql-server" icon="project-diagram" href="https://github.com/honojs/middleware/tree/main/packages/graphql-server">
    GraphQL server middleware

    ```bash theme={null}
    npm install @hono/graphql-server graphql
    ```

    ```typescript theme={null}
    import { graphqlServer } from '@hono/graphql-server'

    app.use('/graphql', graphqlServer({
      schema: yourSchema
    }))
    ```
  </Card>
</CardGroup>

### Template Engines

<CardGroup cols={2}>
  <Card title="@hono/react-renderer" icon="react" href="https://github.com/honojs/middleware/tree/main/packages/react-renderer">
    Server-side React rendering

    ```bash theme={null}
    npm install @hono/react-renderer react react-dom
    ```

    ```typescript theme={null}
    import { reactRenderer } from '@hono/react-renderer'

    app.use(reactRenderer())

    app.get('/', (c) => {
      return c.render(<h1>Hello from React!</h1>)
    })
    ```
  </Card>

  <Card title="@hono/ejs-renderer" icon="file-code" href="https://github.com/honojs/middleware/tree/main/packages/ejs">
    EJS template rendering

    ```bash theme={null}
    npm install @hono/ejs ejs
    ```

    ```typescript theme={null}
    import { ejs } from '@hono/ejs'

    app.use('/views/*', ejs())

    app.get('/views/page', (c) => {
      return c.render('template.ejs', { title: 'Hello' })
    })
    ```
  </Card>
</CardGroup>

### Utilities

<CardGroup cols={2}>
  <Card title="@hono/swagger" icon="book" href="https://github.com/honojs/middleware/tree/main/packages/swagger">
    Swagger/OpenAPI documentation

    ```bash theme={null}
    npm install @hono/swagger
    ```

    ```typescript theme={null}
    import { swaggerUI } from '@hono/swagger'

    app.get('/docs', swaggerUI({ url: '/openapi.json' }))
    ```
  </Card>

  <Card title="@hono/firebase-auth" icon="fire" href="https://github.com/honojs/middleware/tree/main/packages/firebase-auth">
    Firebase Authentication middleware

    ```bash theme={null}
    npm install @hono/firebase-auth firebase-admin
    ```

    ```typescript theme={null}
    import { firebaseAuth } from '@hono/firebase-auth'

    app.use('/api/*', firebaseAuth())
    ```
  </Card>
</CardGroup>

## Creating Middleware Packages

If you're creating a middleware package for others to use:

### Package Structure

```typescript theme={null}
// 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

```json theme={null}
{
  "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

````markdown theme={null}
# hono-my-middleware

A middleware for Hono that does X.

## Installation

```bash
npm install hono-my-middleware
````

## Usage

```typescript theme={null}
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:

<CardGroup cols={2}>
  <Card title="Official Middleware" icon="github" href="https://github.com/honojs/middleware">
    Browse the official Hono middleware repository
  </Card>

  <Card title="npm Search" icon="npm" href="https://www.npmjs.com/search?q=keywords:hono-middleware">
    Search npm for packages tagged with `hono-middleware`
  </Card>
</CardGroup>

## Best Practices

<AccordionGroup>
  <Accordion title="Check compatibility">
    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
  </Accordion>

  <Accordion title="Test thoroughly">
    Always test third-party middleware in a development environment before deploying to production:

    ```typescript theme={null}
    import { describe, it } from 'vitest'

    describe('Third-party middleware integration', () => {
      it('should work with my app', async () => {
        // Test the middleware with your app
      })
    })
    ```
  </Accordion>

  <Accordion title="Handle errors gracefully">
    Wrap third-party middleware in error handlers:

    ```typescript theme={null}
    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)
    ```
  </Accordion>

  <Accordion title="Keep dependencies updated">
    Regularly update middleware packages to get:

    * Security fixes
    * Performance improvements
    * New features
    * Bug fixes

    ```bash theme={null}
    npm update
    npm audit
    ```
  </Accordion>
</AccordionGroup>

## Contributing

If you create a useful middleware, consider:

1. **Open sourcing it** - Share it with the community on GitHub
2. **Publishing to npm** - Make it easy for others to install
3. **Tagging properly** - Use the `hono-middleware` keyword
4. **Documenting well** - Include examples and API documentation
5. **Adding tests** - Ensure it works correctly
6. **Submitting to awesome-hono** - Get it listed in community resources

## Related Topics

<CardGroup cols={2}>
  <Card title="Built-in Middleware" icon="box" href="/middleware/built-in">
    Explore Hono's built-in middleware
  </Card>

  <Card title="Custom Middleware" icon="code" href="/middleware/custom">
    Learn to create your own middleware
  </Card>
</CardGroup>
