Aller au contenu
Français

CORS

Ce contenu n’est pas encore disponible dans votre langue.

CORS is a route directive, not a plain middleware — a preflight OPTIONS request never matches a method-specific route, so a middleware would never run for it. cors(options, child) is a dedicated directive that the compiler expands: it decorates the real responses with the CORS headers and synthesises an OPTIONS preflight route for every pattern in child.

import { cors, CorsOptions, concat, get, path, post } from 'actor-ts/http';
const corsOptions = CorsOptions.create()
.withOrigins('https://app.example', 'https://admin.example')
.withCredentials();
const routes = cors(corsOptions, path('api', concat(
get(listHandler),
post(createHandler),
)));

The compiler adds OPTIONS /api automatically; a browser preflight gets 204 with the Access-Control-Allow-* headers, and the actual GET/POST responses get Access-Control-Allow-Origin + Vary: Origin.

Builder methodFieldPurpose
withOrigins(...o)originsExact-match allowlist.
withAnyOrigin()originsAllow any origin (*). Must be explicit.
withOriginPredicate(predicate)originsDecide per request; a throwing predicate denies.
withMethods(...m)methodsAccess-Control-Allow-Methods. Default: the methods registered at the pattern.
withAllowedHeaders(...h)allowedHeadersDefault: echo the (sanitised) request headers.
withExposedHeaders(...h)exposedHeadersAccess-Control-Expose-Headers.
withCredentials(flag?)credentialsAccess-Control-Allow-Credentials: true.
withMaxAge(seconds)maxAgePreflight cache duration.

Access-Control-Allow-Origin echoes the request origin (the literal * is sent only for withAnyOrigin() without credentials), and Vary: Origin is merged whenever the origin is echoed so caches don’t cross-serve.

  • Security headers — the companion response headers.
  • CSRF — cross-site request forgery protection.
  • Security — the recommended stack + ordering.