# cors

**Kind:** Function

**Source:** [`src/middleware/cors/index.ts`](https://github.com/honojs/hono/blob/main/src/middleware/cors/index.ts#L63)

**Part of:** [Middleware](subsystem-src-middleware)

CORS Middleware for Hono.

`cors` creates Hono middleware that adds Cross-Origin Resource Sharing headers to responses and handles browser preflight requests. Configure it at the app or route scope to control allowed origins, methods, request headers, exposed headers, and credentials.

## Signature

```ts
function cors(options: CORSOptions): MiddlewareHandler
```

## Parameters

| Name | Type |
|---|---|
| `options` | `CORSOptions` |

**Returns:** `MiddlewareHandler`

## Diagram

```mermaid
graph LR
  Request[Incoming request] --> Middleware[cors options]
  Middleware --> Check{Preflight request?}
  Check -->|Yes| Preflight[Return CORS response headers]
  Check -->|No| Next[Run downstream Hono handler]
  Next --> Response[Add CORS response headers]
```

## Usage

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

const app = new Hono()

app.use(
  '/api/*',
  cors({
    origin: 'https://example.com',
    allowMethods: ['GET', 'POST'],
    allowHeaders: ['Content-Type', 'Authorization'],
    credentials: true,
  })
)

app.get('/api/users', (c) => {
  return c.json({ users: [] })
})

export default app
```

## AI Coding Instructions

- Register `cors` before the routes that need CORS headers, using `app.use()` with an appropriate path scope.
- Set a specific `origin` when `credentials` is enabled; browsers reject credentialed responses with a wildcard origin.
- Configure `allowMethods` and `allowHeaders` to match the methods and headers sent by browser clients.
- Do not add separate `OPTIONS` handlers for routes covered by this middleware unless custom preflight behavior is required.
