


Simple CORS-handling for any itty-router API. Designed on Cloudflare Workers, but works anywhere.
Features
- Tiny. Currently ~600 bytes, with zero-dependencies.
- Fully Typed/TypeScript
- Granular control over allowed methods, origins, etc.
- handles OPTIONS preflight requests
- response processor (
corsify
) can be used per-response, or globally downstream
!! Breaking API Changes (pre v1.x)!!
You're using an early-access package. Until itty-cors hits a stable v1.0 release, API changes will be broadcasted as minor version bumps.
Simple Usage
import { Router } from 'itty-router'
import { error, json, missing } from 'itty-router-extras'
import { createCors } from 'itty-cors'
const { preflight, corsify } = createCors()
const router = Router()
router
.all('*', preflight)
.get('/version', () => json({ version: '0.1.0' }))
.get('/stuff', () => json(['foo', 'bar', 'baz']))
.all('*', () => missing('Are you sure about that?'))
export default {
fetch: (...args) => router
.handle(...args)
.catch(err => error(500, err.stack))
.then(corsify)
}
CORS enabled on a single route (and advanced options)
import { Router } from 'itty-router'
import { error, json, missing } from 'itty-router-extras'
import { createCors } from 'itty-cors'
const { preflight, corsify } = createCors({
methods: ['GET', 'POST', 'DELETE'],
origins: ['*'],
maxAge: 3600,
headers: {
'my-custom-header': 'will be injected with each CORS-enabled response',
},
})
const router = Router()
router
.all('*', preflight)
.get('/version', () => corsify(json({ version: '0.1.0' })))
.get('/stuff', () => json(['foo', 'bar', 'baz']))
.all('*', () => missing('Are you sure about that?'))
export default {
fetch: (...args) => router
.handle(...args)
.catch(err => error(500, err.stack))
}
API
createCors(options?) => { preflight: function, corsify: function }
Returns an object with two properties, preflight
(a preflight OPTIONS middleware), and corsify
(a response-handling function).
Option | Type(s) | Default | Description |
---|
origins | string[] | ['*'] | By default, all origins are allowed (most common). Modify this to restrict to specific origins. |
maxAge | number | 3600 | Set the expiry of responses |
methods | string[] | ['GET'] | Define which methods are allowed. OPTIONS will be automatically added. |
headers | object | {} | Add any custom headers to be injected with CORS-enabled responses. |
preflight(request: Request) => Response
This is the preflight middleware to be injected upstream on options requests.
router.options('*', preflight)
corsify(response: Response) => Response
This wrapper injects CORS headers into a response, if not already set (upstream). Use this at the end of the router.handle
Promise chain to CORS-enable all responses/the entire API, or wrap any response generator (e.g. json()
from itty-router-extras) to make a single CORS-enabled response.