Skip to main content

Import

Usage

Options

The cors middleware accepts an optional CORSOptions object:
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
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.
string[]
default:[]
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.
number
The value of “Access-Control-Max-Age” CORS header. Indicates how long the results of a preflight request can be cached.
boolean
The value of “Access-Control-Allow-Credentials” CORS header. Set to true to allow credentials (cookies, authorization headers).
string[]
default:[]
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: Origin header when origin is not *
  • Reflects Access-Control-Request-Headers if allowHeaders is not specified
  • Removes Content-Length and Content-Type headers from preflight responses
  • If origin validation function returns null/undefined, the origin is denied