---
title: "Configuring Middleware"
description: "Middleware functions in Hono intercept incoming HTTP requests and outgoing responses. They allow you to attach cross-cutting features—such as security headers, CORS protection, JWT or bearer authen..."
last_updated: "2026-10-12T08:15:16.248386+00:00"
canonical_url: "https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/guide/how-to-guides/configuring-middleware"
---

## Overview

Middleware functions in Hono intercept incoming HTTP requests and outgoing responses. They allow you to attach cross-cutting features—such as security headers, CORS protection, JWT or bearer authentication, body payload limits, and request logging—globally or to specific route patterns. 

This guide covers how to set up and configure these standard middleware utilities using Hono's public API.

---

## Security Headers (`secureHeaders`)

### Introduction to Secure Headers

The secure headers middleware adds standard HTTP security headers (such as Content Security Policy, X-Frame-Options, and Strict-Transport-Security) to your responses and removes exposing headers like `X-Powered-By`.

### Usage Example

```typescript
import { Hono } from 'hono'
import { secureHeaders } from 'hono/secure-headers'

const app = new Hono()

// Apply default secure headers globally
app.use(secureHeaders())

app.get('/', (c) => c.text('Protected by secure headers!'))
```

> [!TIP]
> You can customize individual headers or pass specific Content Security Policy (CSP) directives by supplying an options object to `secureHeaders()`.

---

## Cross-Origin Resource Sharing (`cors`)

### Introduction to CORS

The CORS middleware manages response headers to control how browser applications from different domains can access your resources.

### Usage Example

```typescript
import { Hono } from 'hono'
import { cors } from 'hono/cors'

const app = new Hono()

// Allow specific origins and configure credentials
app.use(
  '/api/*',
  cors({
    origin: 'http://example.com',
    allowHeaders: ['X-Custom-Header', 'Upgrade-Insecure-Requests'],
    allowMethods: ['POST', 'GET', 'OPTIONS'],
    exposeHeaders: ['Content-Length', 'X-Kuma-Revision'],
    maxAge: 600,
    credentials: true,
  })
)
```

---

## Authentication Middleware

### Introduction to Authentication

Hono provides multiple built-in mechanisms to secure your routes via token verification.

### JWT Authentication (`jwt`)

The JWT middleware validates JSON Web Tokens passed via the `Authorization` header or cookies.

```typescript
import { Hono } from 'hono'
import { jwt } from 'hono/jwt'

const app = new Hono()

app.use(
  '/auth/*',
  jwt({
    secret: 'it-is-very-secret',
    alg: 'HS256',
  })
)

app.get('/auth/page', (c) => {
  const payload = c.get('jwtPayload')
  return c.json({ message: 'Authorized', payload })
})
```

> [!IMPORTANT]
> The JWT middleware requires a runtime supporting cryptographic operations (`crypto.subtle.importKey`).

Supported algorithms for verification in `jwt`:
- Supported signing algorithms: `HS256`, `HS384`, `HS512`, `RS256`, `RS384`, `RS512`, `PS256`, `PS384`, `PS512`, `ES256`, `ES384`, `ES512`, `EdDSA`
- Sources: `src/middleware/jwt/jwt.ts`

### Bearer Token Authentication (`bearerAuth`)

The bearer auth middleware validates raw bearer tokens against a static string, array of strings, or a custom verification function.

```typescript
import { Hono } from 'hono'
import { bearerAuth } from 'hono/bearer-auth'

const app = new Hono()

app.use('/api/*', bearerAuth({ token: 'my-secret-token' }))

app.get('/api/data', (c) => c.text('Access granted'))
```

### JWK Authentication (`jwk`)

The JWK middleware validates asymmetric JWTs using JSON Web Keys provided directly or fetched via a `jwks_uri`.

```typescript
import { Hono } from 'hono'
import { jwk } from 'hono/jwk'

const app = new Hono()

app.use(
  '/api/*',
  jwk({
    jwks_uri: 'https://auth.example.com/.well-known/jwks.json',
    alg: ['RS256'],
  })
)
```

---

## Payload and Request Controls

### Body Size Limits (`bodyLimit`)

The body limit middleware restricts incoming request payload sizes, returning a `413 Payload Too Large` status code when exceeded.

```typescript
import { Hono } from 'hono'
import { bodyLimit } from 'hono/body-limit'

const app = new Hono()

app.post(
  '/upload',
  bodyLimit({
    maxSize: 50 * 1024, // 50 KB limit
    onError: (c) => c.text('File is too large!', 413),
  }),
  async (c) => {
    return c.text('Upload successful!')
  }
)
```

### CSRF Protection (`csrf`)

The CSRF middleware protects your endpoints by validating request origins and `Sec-Fetch-Site` headers for state-changing HTTP methods.

```typescript
import { Hono } from 'hono'
import { csrf } from 'hono/csrf'

const app = new Hono()

// Require matching origin or same-origin fetch site
app.use('*', csrf())
```

---

## Logging (`logger`)

### Introduction to Logger

The logger middleware prints incoming requests and outgoing responses (including HTTP status and elapsed execution time) to the console or a custom output function.

### Usage Example

```typescript
import { Hono } from 'hono'
import { logger } from 'hono/logger'

const app = new Hono()

// Enable default console logger
app.use(logger())

app.get('/', (c) => c.text('Hello Hono!'))
```

---

## Configuration Reference Summary

| Middleware | Import Path | Primary Options / Configuration |
| :--- | :--- | :--- |
| **Secure Headers** | `hono/secure-headers` | `contentSecurityPolicy`, `xFrameOptions`, `strictTransportSecurity`, `removePoweredBy` |
| **CORS** | `hono/cors` | `origin`, `allowMethods`, `allowHeaders`, `maxAge`, `credentials`, `exposeHeaders` |
| **JWT Auth** | `hono/jwt` | `secret`, `alg`, `headerName`, `cookie`, `verification` |
| **Bearer Auth** | `hono/bearer-auth` | `token`, `verifyToken`, `realm`, `prefix`, `headerName`, `hashFunction` |
| **JWK Auth** | `hono/jwk` | `keys`, `jwks_uri`, `alg`, `allow_anon`, `headerName`, `verification` |
| **Body Limit** | `hono/body-limit` | `maxSize`, `onError` |
| **CSRF** | `hono/csrf` | `origin`, `secFetchSite` |
| **Logger** | `hono/logger` | `fn` (custom print function) |

> [!WARNING]
> Always mount security and authentication middleware *before* your route handlers so that incoming requests are properly filtered and verified before execution reaches your business logic.

## Related

- [Routing and Handlers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/guide/getting-started/routing-and-handlers)
- [Errors and Exceptions](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/guide/troubleshooting/errors-and-exceptions)


## Sitemap

See the full [sitemap](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/llms.txt) for all pages in this wiki.
