Kest

Search

Search the documentation

Security

CORS

Let a web page from one site call your API on another.

Browsers enforce the same-origin policy: a script on https://app.example.com may not read responses from https://api.example.com (a different origin: scheme, host or port differs), unless the API says it is allowed. CORS (Cross-Origin Resource Sharing) is how the API says so, with Access-Control-* headers. It is a browser rule: tools like curl, servers and mobile apps ignore it, so CORS protects users' browsers, not your API.

Loading diagram…
app.http(adapter) {
    enableCors(CorsOptions(
        origins = listOf("https://app.example.com"),          // "*" allows any origin; list yours in production
        methods = listOf("GET", "POST", "PUT", "PATCH", "DELETE"),
        allowedHeaders = emptyList(),                          // empty: reflect what the browser asks for
        exposedHeaders = listOf("x-request-id"),               // response headers the page's script may read
        credentials = true,                                    // allow cookies; never combine with origins = "*"
        maxAgeSeconds = 86_400,                                // how long a browser may cache the preflight answer
    ))
}

The middleware answers OPTIONS preflight requests itself, before routing, and adds the Access-Control-* headers to other responses. A request from an origin that is not listed gets no CORS headers, so the browser blocks the page from reading the answer.

The common situations

SituationSetting
A public API anyone's page may call, no cookiesorigins = listOf("*")
Your own front end on another domainorigins = listOf("https://app.example.com")
Cookies or Authorization sent from the browseran explicit origin list and credentials = true (* with credentials is refused by browsers)
Front end and API on the same originno CORS at all (Next.js: one address)

Things people get wrong

  • CORS is not security for your API. It does not stop attackers' scripts or curl; authentication does. Never rely on it to protect data.
  • A CORS error in the browser console is often a symptom: the request also failed (a 500, or a missing route), and the failed response has no CORS headers. Look at the network tab.
  • A request with a custom header or JSON body triggers a preflight: make sure OPTIONS reaches Kest (a proxy must not swallow it).
  • Cookies across different sites also need SameSite=None; Secure; same-origin avoids this.

Read more