Skip to content

CORS

CorsMiddleware handles CORS preflight requests and response headers.

// Allow all origins (development)
server.use(CorsMiddleware())
// Or use the development preset
server.use(CorsMiddleware.development())
server.use(CorsMiddleware(CorsMiddleware.Options(
origin = Origin.Multiple(Set(
"https://app.example.com",
"https://admin.example.com",
)),
methods = Set("GET", "POST", "PUT", "DELETE"),
allowedHeaders = Set("Content-Type", "Authorization"),
exposedHeaders = Set("X-Total-Count"),
credentials = true,
maxAge = Some(3600),
)))
OptionTypeDefaultDescription
originOriginOrigin.AnyAllowed origins
methodsSet[String]GET, HEAD, PUT, PATCH, POST, DELETEAllowed methods
allowedHeadersSet[String]Content-Type, AuthorizationAllowed request headers
exposedHeadersSet[String]Set.emptyHeaders exposed to the browser
credentialsBooleanfalseAllow credentials
maxAgeOption[Int]Some(86400)Preflight cache duration (seconds)
preflightSuccessStatusInt204Status code for preflight responses
// Any origin
Origin.Any
// Single origin
Origin("https://example.com")
// Multiple origins
Origin(Set("https://app.example.com", "https://admin.example.com"))
// Regex pattern
Origin.pattern("""https://.*\.example\.com""")
// Custom validation function
Origin.validate(origin =>
origin.endsWith(".example.com") && origin.startsWith("https://")
)

Permissive settings for local development:

server.use(CorsMiddleware.development())

Strict settings with specific allowed origins:

server.use(CorsMiddleware.production(Set(
"https://app.example.com",
"https://admin.example.com",
)))
  • Preflight requests (OPTIONS with Origin and Access-Control-Request-Method) are handled automatically and return the configured CORS headers
  • Simple requests get CORS headers added via a response finalizer
  • Origin validation is checked against the configured Origin type