Import
Usage
Options
Thecors middleware accepts an optional CORSOptions object:
origin
string | string[] | ((origin: string, c: Context) => string | undefined | null | Promise<string | undefined | null>)
default:"*"
The value of “Access-Control-Allow-Origin” CORS header. Can be:
- A single origin string (e.g.,
'http://example.com') - An array of allowed origins
- A function that returns the allowed origin or null/undefined to deny
allowMethods
string[] | ((origin: string, c: Context) => string[] | Promise<string[]>)
default:["GET","HEAD","PUT","POST","DELETE","PATCH"]
The value of “Access-Control-Allow-Methods” CORS header. Can be an array of methods or a function that returns the array.
The value of “Access-Control-Allow-Headers” CORS header. If not specified, reflects the headers specified in the request’s “Access-Control-Request-Headers” header.
The value of “Access-Control-Max-Age” CORS header. Indicates how long the results of a preflight request can be cached.
The value of “Access-Control-Allow-Credentials” CORS header. Set to
true to allow credentials (cookies, authorization headers).The value of “Access-Control-Expose-Headers” CORS header. Indicates which headers can be exposed to the client.
Signature
Examples
Basic usage (allow all origins)
Specific origin
Multiple origins
Custom allowed methods
With credentials
Custom headers
Dynamic origin validation
Async origin validation
Behavior
- Automatically handles preflight OPTIONS requests
- Returns 204 No Content for successful preflight requests
- Sets
Vary: Originheader when origin is not* - Reflects
Access-Control-Request-HeadersifallowHeadersis not specified - Removes
Content-LengthandContent-Typeheaders from preflight responses - If origin validation function returns null/undefined, the origin is denied