CORS inside WKWebView trips up a lot of teams because it feels like “Safari in my app,” until it very much doesn’t.
I’ve seen the same pattern over and over: the API works in desktop Chrome, maybe even in Safari, but the iOS app throws a vague CORS error, cookies disappear, preflights fail, or local bundled content can’t talk to the backend. Then someone suggests turning off security. Don’t.
Here are the common mistakes I see with CORS in WKWebView, why they happen, and the clean fixes.
Mistake #1: Assuming WKWebView gets special CORS treatment
It doesn’t. WKWebView enforces web security rules like a browser. If your frontend is making cross-origin fetch() or XHR calls, your server still needs proper CORS headers.
A lot of mobile teams think “it’s a native app, so CORS shouldn’t apply.” That’s only true if you make requests through native networking like URLSession. Inside WKWebView, the JavaScript runtime is still subject to browser-origin rules.
Broken assumption
fetch("https://api.example.com/user", {
credentials: "include"
})
And the server returns only:
Access-Control-Allow-Origin: *
That will fail if credentials are involved.
Fix
If you use cookies or HTTP auth, return a specific origin, not *.
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
Vary: Origin
If you truly have a public, anonymous API, * is fine. GitHub’s API is a good real-world example for non-credentialed access:
access-control-allow-origin: *
access-control-expose-headers: ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Resource, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, X-GitHub-SSO, X-GitHub-Request-Id, Deprecation, Sunset, Warning
That works because the resource is designed to be readable cross-origin without cookies.
Mistake #2: Loading local HTML and expecting your API to trust null
This one is classic.
If you load HTML from app bundle files using loadFileURL, requests may come from an unusual origin, commonly null. Many backends don’t account for that, and honestly, blindly allowing null is usually a bad idea.
What it looks like
You bundle index.html in the app:
webView.loadFileURL(fileURL, allowingReadAccessTo: fileURL.deletingLastPathComponent())
Then your JS does:
fetch("https://api.example.com/data")
The browser sends an Origin: null header. Your server doesn’t allow it. CORS fails.
Bad fix
Access-Control-Allow-Origin: null
I don’t recommend this unless you fully understand the trust boundary. null origins can come from more than just your app bundle.
Better fixes
Option 1: Serve app content from HTTPS
Host the web app on a real origin like:
https://app.example.com
Then your API can safely allow that explicit origin.
Option 2: Use a custom app-bound scheme carefully
You can use WKURLSchemeHandler for app content, but remember: custom schemes are not a free pass around CORS. You still need to understand what origin the page gets and how your API validates it.
Option 3: Move API calls to native code
If the web content is local-only and you control the app, bridge requests through Swift with URLSession, then send results back into JS.
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: URL(string: "https://api.example.com/data")!) { data, response, error in
guard let data = data,
let json = String(data: data, encoding: .utf8) else { return }
DispatchQueue.main.async {
let script = "window.handleNativeResponse(\(json));"
webView.evaluateJavaScript(script)
}
}
task.resume()
That changes the trust model, though. You’re no longer relying on browser CORS for that request path.
Mistake #3: Forgetting preflight requests exist
If your web app sends JSON, custom headers, or non-simple methods, WKWebView will trigger a preflight OPTIONS request just like other browsers.
Teams often test with a simple GET first, then later add Authorization or Content-Type: application/json and suddenly “iOS broke it.”
iOS didn’t break it. Your server never handled preflight correctly.
Common trigger
fetch("https://api.example.com/profile", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer token"
},
body: JSON.stringify({ name: "Lee" })
})
Required server response
Your server needs to answer the OPTIONS request with something like:
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true
Vary: Origin
And yes, the OPTIONS route must actually return those headers. I still see APIs that set CORS on GET and POST responses but forget OPTIONS.
Express example
app.use((req, res, next) => {
const origin = req.headers.origin;
const allowedOrigins = new Set(["https://app.example.com"]);
if (allowedOrigins.has(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Vary", "Origin");
}
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
if (req.method === "OPTIONS") {
return res.status(204).end();
}
next();
});
Mistake #4: Trying to read headers that aren’t exposed
Your request may succeed, but your JS still can’t read useful response headers unless the server exposes them.
This bites people with pagination, rate limiting, and caching metadata.
For example, if your API returns ETag or Link, your frontend can’t reliably read them unless they’re listed in Access-Control-Expose-Headers.
GitHub does this well. Their real header includes:
access-control-expose-headers: ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Resource, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, X-GitHub-SSO, X-GitHub-Request-Id, Deprecation, Sunset, Warning
Symptom
const res = await fetch("https://api.example.com/items");
console.log(res.headers.get("ETag")); // null
console.log(res.headers.get("Link")); // null
Fix
Expose what your app genuinely needs:
Access-Control-Expose-Headers: ETag, Link, X-RateLimit-Remaining
Don’t dump every header out of laziness. Be intentional.
Mistake #5: Reflecting any Origin header
I get why people do this. It makes the support tickets stop. It also turns CORS into theater.
Dangerous pattern
res.setHeader("Access-Control-Allow-Origin", req.headers.origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
No validation. No allowlist. Every site becomes trusted.
That’s not “CORS enabled.” That’s “whoever asks, gets in.”
Fix
Validate origins against a strict allowlist.
const allowedOrigins = new Set([
"https://app.example.com",
"https://staging-app.example.com"
]);
const origin = req.headers.origin;
if (allowedOrigins.has(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Vary", "Origin");
}
If you need wildcard support for subdomains, implement that carefully and explicitly. Don’t just reflect.
Mistake #6: Mixing cookies with modern browser defaults and blaming CORS
Sometimes the console says “CORS,” but the real problem is cookies not being sent or accepted.
For session-based auth in WKWebView, your cookie attributes need to be compatible with cross-site usage.
Typical setup that fails
Your app page is on one origin:
https://app.example.com
Your API is on another:
https://api.example.com
You authenticate with cookies, but the cookie lacks the right attributes.
Fix
Use cookies with appropriate attributes, typically:
Set-Cookie: session=abc123; Path=/; Secure; HttpOnly; SameSite=None
And pair that with:
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
On the client:
fetch("https://api.example.com/me", {
credentials: "include"
})
If you’re debugging cookie behavior, don’t stop at CORS headers. Check the cookie attributes too.
Mistake #7: Disabling web security in development and carrying bad assumptions into production
A lot of CORS confusion starts with dev shortcuts: local proxies, disabled checks, simulator-only hacks, or native wrappers that bypass the browser path.
Then production uses real WKWebView behavior and things fall apart.
My rule is simple: test with the same origin model you plan to ship.
If production is:
- web app on
https://app.example.com - API on
https://api.example.com
then your staging setup should behave the same way. Same scheme, same cookie model, same preflight behavior.
You’ll save yourself days of fake debugging.
Mistake #8: Treating CORS as the whole security model
CORS is a browser read-control mechanism. It is not authentication, authorization, CSRF protection, or content hardening.
If you’re embedding remote content in WKWebView, you should also think about:
- Content Security Policy
- navigation restrictions
- script injection boundaries
- message handler exposure between JS and native
If you need a CSP refresher, https://csp-guide.com is a solid reference. For Apple-specific behavior, stick to the official WKWebView docs and WebKit documentation.
A practical setup that usually works
For a hosted web app inside WKWebView, talking to a cookie-authenticated API:
Server
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Expose-Headers: ETag, Link, X-RateLimit-Remaining
Vary: Origin
Cookie
Set-Cookie: session=abc123; Path=/; Secure; HttpOnly; SameSite=None
Client
fetch("https://api.example.com/account", {
method: "GET",
credentials: "include"
});
Preflight support
Return a valid 204 or 200 response to OPTIONS with the same relevant CORS headers.
What I’d do first when WKWebView CORS breaks
- Inspect the
Originheader actually being sent. - Check whether the request is simple or preflighted.
- Verify
OPTIONSresponses, not just the final request. - If cookies are involved, check
SameSite,Secure, andcredentials: "include". - If JS needs response headers, confirm
Access-Control-Expose-Headers. - If content is loaded from local files, rethink the origin model before whitelisting
null.
Most WKWebView CORS bugs are not exotic. They’re usually standard browser CORS bugs with an iOS-shaped wrapper. Treat WKWebView like a real browser, keep your origin model explicit, and resist the urge to “just allow everything.” That fix always comes back to bite later.