CORS
CorsMiddleware handles CORS preflight requests and response headers.
Basic Usage
Section titled “Basic Usage”// Allow all origins (development)server.use(CorsMiddleware())
// Or use the development presetserver.use(CorsMiddleware.development())Configuration
Section titled “Configuration”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),)))Options
Section titled “Options”| Option | Type | Default | Description |
|---|---|---|---|
origin | Origin | Origin.Any | Allowed origins |
methods | Set[String] | GET, HEAD, PUT, PATCH, POST, DELETE | Allowed methods |
allowedHeaders | Set[String] | Content-Type, Authorization | Allowed request headers |
exposedHeaders | Set[String] | Set.empty | Headers exposed to the browser |
credentials | Boolean | false | Allow credentials |
maxAge | Option[Int] | Some(86400) | Preflight cache duration (seconds) |
preflightSuccessStatus | Int | 204 | Status code for preflight responses |
Origin Types
Section titled “Origin Types”// Any originOrigin.Any
// Single originOrigin("https://example.com")
// Multiple originsOrigin(Set("https://app.example.com", "https://admin.example.com"))
// Regex patternOrigin.pattern("""https://.*\.example\.com""")
// Custom validation functionOrigin.validate(origin => origin.endsWith(".example.com") && origin.startsWith("https://"))Presets
Section titled “Presets”Development
Section titled “Development”Permissive settings for local development:
server.use(CorsMiddleware.development())Production
Section titled “Production”Strict settings with specific allowed origins:
server.use(CorsMiddleware.production(Set( "https://app.example.com", "https://admin.example.com",)))How It Works
Section titled “How It Works”- Preflight requests (OPTIONS with
OriginandAccess-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
Origintype