CORS Middleware
When your API is consumed by a browser app on a different domain, browsers enforce Cross-Origin Resource Sharing (CORS). Prism’s PrismCORSMiddleware handles the OPTIONS preflight requests and response headers automatically.
Quick Setup
await server.use(PrismCORSMiddleware(allowedOrigins: ["*"]))
Using "*" allows any website to call your API. Fine for public APIs and development, but restrict origins in production.
Production Configuration
await server.use(PrismCORSMiddleware(
allowedOrigins: [
"https://myapp.com",
"https://staging.myapp.com"
],
allowedMethods: [.GET, .POST, .PUT, .DELETE],
allowCredentials: true
))
SPA Frontend Pattern
A typical setup when your Swift API serves a React/Vue/Angular frontend:
let cors = PrismCORSMiddleware(
allowedOrigins: ["https://app.example.com"],
allowedMethods: [.GET, .POST, .PUT, .PATCH, .DELETE],
allowCredentials: true // Needed for cookies/auth headers
)
await server.use(cors)
await server.group("/api") { api in
api.get("/me") { request in
// Browser can now call this from app.example.com
.json(["user": "Alice"])
}
}
How It Works
- Preflight: Browser sends
OPTIONS request before the real request. CORS middleware responds with allowed origins/methods/headers.
- Actual request: Middleware adds
Access-Control-Allow-Origin and related headers to the response.
If you’re only building a mobile app or server-to-server API, you don’t need CORS at all — it’s a browser-only security mechanism.