h3-native CORS event handler
This package has been integrated to h3 v1.5.0, so you can import all features of this package from h3 directly. 🎉
This repository and the npm package has been archived.
Thank you for all kinds of contribution to this package!
Install package:
# npm
npm install @nozomuikuta/h3-cors
# yarn
yarn add @nozomuikuta/h3-cors
# pnpm
pnpm install @nozomuikuta/h3-corsImport:
// ESM
import { defineCorsEventHandler } from '@nozomuikuta/h3-cors'
// CommonJS
const { defineCorsEventHandler } = require('@nozomuikuta/h3-cors')Usage:
import { createServer } from 'http'
import { createApp } from 'h3'
import { defineCorsEventHandler } from '@nozomuikuta/h3-cors'
const app = createApp()
app.use(defineCorsEventHandler({ /* options */ }))
app.use('/', () => 'Hello world!')
createServer(app).listen(process.env.PORT || 3000)originis either of the following values to configure Access-Control-Allow-Origin CORS header"*"(default)"null"- array of strings or regular expressions
- function that receives value of Origin header and returns boolean
- If
falseis returned, an error is thrown
- If
methodsis"*"or an array of HTTP methods to configures Access-Control-Allow-Methods CORS header (default:"*")allowHeadersis"*"or an array of HTTP headers to configure Access-Control-Allow-Headers CORS header (default:"*")exposeHeadersis"*"or an array of HTTP headers to configure Access-Control-Expose-Headers CORS header (default:"*")credentialsis boolean to configure Access-Control-Allow-Credentials CORS header (default:false)maxAgeis a string to configure Access-Control-Max-Age, orfalseto unset the header (default:false)preflight.statusCodeis used to setevent.res.statusCodefor preflight request (default:204)
interface CorsOptions {
origin?: '*' | 'null' | (string | RegExp)[] | ((origin: string) => boolean)
methods?: '*' | HTTPMethod[]
allowHeaders?: '*' | string[]
exposeHeaders?: '*' | string[]
credentials?: boolean
maxAge?: string | false
preflight?: {
statusCode?: number
}
}You can import utility functions as well as event handler.
isPreflight(event)isAllowedOrigin(origin, options)appendCorsPreflightHeaders(event, options)appendCorsActualRequestHeaders(event, options)
- Clone this repository
- Install latest LTS version of Node.js
- Enable Corepack using
corepack enable - Install dependencies using
pnpm install - Run interactive tests using
pnpm dev
Made with 💛
Published under MIT License.