CORS Handling Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓CORS Handling runs in O(1) time and O(1) space, in Swift as in every other language.
- ✓Two different worlds answer to the same language name here. URLSession does not enforce CORS at all, because it is not a browser: a native client reads every response header whatever the policy says, while a WKWebView on the same device applies the full protocol.
- ✓Because Vapor is protocol-oriented, the policy is a struct adopting AsyncMiddleware rather than a subclass of anything, and it is installed with app.middleware.use(_:at: .beginning).
- ✓The Swift trap: Vapor places ErrorMiddleware at the front of the chain by default. Register your CORS middleware with app.middleware.use(cors) and it lands inside that, so when a route throws Abort(.unauthorized) the throw propagates outward past your await, the error middleware converts it into a Response, and the code after your await never executes: the browser receives a bare 401 with no Allow-Origin and reports a CORS failure that conceals the authentication bug.
- ✓The middleware chain is folded into a single linked responder at boot, so a request pays one protocol witness call rather than a lookup.
What CORS Handling actually is
CORS Handling in Swift: what you actually reach for
Swift implementation
import Vapor
/// Vapor ships CORSMiddleware, but its .originBased setting echoes whatever Origin
/// arrived. Paired with credentials that is a wildcard in disguise, so this middleware
/// keeps an explicit allowlist and never lets the caller name itself.
struct AllowlistCORS: AsyncMiddleware {
static let allowed: Set<String> = ["https://app.example.dev", "https://ops.example.dev"]
static let exposed = "X-Request-Id, X-Rate-Limit-Remaining"
func respond(to request: Request, chainingTo next: any AsyncResponder) async throws -> Response {
let origin = request.headers.first(name: "Origin")
let ok = origin.map(Self.allowed.contains) ?? false
let isPreflight = request.method == .OPTIONS
&& request.headers.first(name: "Access-Control-Request-Method") != nil
let response: Response
if isPreflight {
// Answer here: routing would reject an OPTIONS that no route declares.
response = Response(status: .noContent)
if ok {
response.headers.replaceOrAdd(name: "Access-Control-Allow-Methods", value: "GET, POST, PATCH")
response.headers.replaceOrAdd(name: "Access-Control-Allow-Headers", value: "Content-Type, Authorization")
response.headers.replaceOrAdd(name: "Access-Control-Max-Age", value: "600")
}
response.headers.add(name: "Vary", value: "Access-Control-Request-Headers")
} else {
response = try await next.respond(to: request)
}
response.headers.add(name: "Vary", value: "Origin")
if ok, let origin {
response.headers.replaceOrAdd(name: "Access-Control-Allow-Origin", value: origin)
response.headers.replaceOrAdd(name: "Access-Control-Allow-Credentials", value: "true")
response.headers.replaceOrAdd(name: "Access-Control-Expose-Headers", value: Self.exposed)
}
return response
}
}
public func configure(_ app: Application) async throws {
// .beginning puts this outside ErrorMiddleware. Registered after it, a thrown Abort
// is converted to a Response that never unwinds back through this middleware.
app.middleware.use(AllowlistCORS(), at: .beginning)
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for CORS Handling?
Two different worlds answer to the same language name here. URLSession does not enforce CORS at all, because it is not a browser: a native client reads every response header whatever the policy says, while a WKWebView on the same device applies the full protocol. Server side the answer is Vapor, which supplies CORSMiddleware and CORSMiddleware.Configuration. Headers are NIO's HTTPHeaders from NIOHTTP1, offering first(name:), add(name:value:) and replaceOrAdd(name:value:); custom policies adopt AsyncMiddleware, a protocol with a single respond(to:chainingTo:) requirement.
What is the most common Swift mistake when implementing CORS Handling?
Vapor places ErrorMiddleware at the front of the chain by default. Register your CORS middleware with app.middleware.use(cors) and it lands inside that, so when a route throws Abort(.unauthorized) the throw propagates outward past your await, the error middleware converts it into a Response, and the code after your await never executes: the browser receives a bare 401 with no Allow-Origin and reports a CORS failure that conceals the authentication bug. Registering at: .beginning fixes it. The related trap is CORSMiddleware's .originBased setting, which echoes whatever Origin arrived and, with credentials on, grants every site authenticated read access.
How does CORS Handling actually perform in Swift?
The middleware chain is folded into a single linked responder at boot, so a request pays one protocol witness call rather than a lookup. HTTPHeaders keeps name and value pairs in a flat array and compares names case-insensitively, so first(name:) is a short linear scan instead of a hash probe, which is fine for four CORS headers and worth hoisting inside a loop. The preflight branch allocates one Response object and returns without ever suspending, so the runtime creates no continuation and the event loop thread is never yielded. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for GitHub Copilot, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.