March Docs

Cors

lib/cors.march — Cors

CORS (Cross-Origin Resource Sharing) middleware for Bastion. Off by default — call Cors.allow/2 only on routes that need it.

Usage in your router:

-- Apply CORS to all API routes
fn route(conn, method, Cons("api", rest)) do
  conn
  |> Cors.allow(Cors.config(["https://frontend.myapp.com"]))
  |> MyApp.API.route(method, rest)
end

-- Handle OPTIONS preflight for API routes
fn route(conn, :options, Cons("api", _)) do
  conn
  |> Cors.allow(Cors.config(["https://frontend.myapp.com"]))
  |> HttpServer.send_resp(204, "")
end

For wildcard origins (development or public APIs):

conn |> Cors.allow(Cors.config_open())

For credentialed requests (cookies / Authorization header):

conn |> Cors.allow(Cors.config_credentialed(["https://frontend.myapp.com"]))

Types

typeCorsConfigCorsConfig = {#

Functions

fnallowallow(conn, cfg)#

Apply CORS headers to the response based on the config.

For simple requests: sets Access-Control-Allow-Origin (if request Origin
matches), Access-Control-Allow-Credentials, and any exposed headers.

For preflight (OPTIONS) requests: also sets Access-Control-Allow-Methods,
Access-Control-Allow-Headers, and Access-Control-Max-Age. The caller is
responsible for sending the 204 response for preflight routes.

If the request has no Origin header, or the origin is not in the allowed
list, no CORS headers are added (the request is treated as same-origin).

    conn |> Cors.allow(Cors.config(["https://frontend.myapp.com"]))
fnconfigconfig(origins)#

Build a basic CORS config for the given origins list. Default methods: GET, POST, PUT, PATCH, DELETE, OPTIONS. Default request headers: content-type, authorization. No credentials (cookies not sent cross-origin).

    Cors.config(["https://frontend.myapp.com", "https://staging.myapp.com"])
fnconfig_credentialedconfig_credentialed(origins)#

Credentialed CORS config for the given origins. Allows cookies and Authorization headers cross-origin. Wildcard origins are not allowed with credentials:true per the spec; always pass explicit origins.

    Cors.config_credentialed(["https://app.myapp.com"])
fnconfig_openconfig_open()#

Open CORS config (wildcard origin). Suitable for fully public APIs. Credentials are disabled (not allowed with wildcard origin per the spec).

    conn |> Cors.allow(Cors.config_open())