Kind: Function
Source: src/middleware/cors/index.ts
Part of: 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
tsfunction cors(options: CORSOptions): MiddlewareHandler
Parameters
| Name | Type |
|---|---|
options | CORSOptions |
Returns: MiddlewareHandler
Diagram
mermaidgraph 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
tsimport { 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
corsbefore the routes that need CORS headers, usingapp.use()with an appropriate path scope. - Set a specific
originwhencredentialsis enabled; browsers reject credentialed responses with a wildcard origin. - Configure
allowMethodsandallowHeadersto match the methods and headers sent by browser clients. - Do not add separate
OPTIONShandlers for routes covered by this middleware unless custom preflight behavior is required.
Was this page helpful?