CORS Errors When Trying to Fetch a File Using Capacitor

3 replies
Last updated: Jul 26, 2022
I am writing an app using Capacitor which allows you to use web tech in iOS/Android. But on iOS, the URL schema is capacitor://localhost/PAGE , etc. I am getting CORS errors when I try to fetch a file uploaded to Sanity because I cannot add capacitor://localhost as a valid CORS origin. I am getting
Failed to load resource: Origin <capacitor://localhost> is not allowed by Access-Control-Allow-Origin. Status code: 403

AI Update

Good news! You can absolutely add capacitor://localhost as a CORS origin in Sanity - you just need to use the Sanity CLI to do it, since the management dashboard doesn't support custom protocol schemes like capacitor://.

The solution is straightforward. Run this command in your terminal:

sanity cors add capacitor://localhost

This will add the Capacitor origin scheme to your project's CORS allowlist, which should resolve your 403 errors when fetching Sanity assets from your iOS/Android app.

Why the management dashboard doesn't work for this:

The CORS configuration UI at manage.sanity.io is designed primarily for standard HTTP/HTTPS origins. Custom protocol schemes like capacitor://localhost aren't supported in the web interface, but the CLI handles them just fine.

Alternative approach using Capacitor HTTP plugin:

If you continue to have issues (particularly with the Asset CDN, since CORS settings don't automatically apply there), consider using the @capacitor-community/http plugin instead of standard fetch. This native HTTP plugin bypasses browser CORS restrictions entirely since it makes requests at the native layer rather than through the WebView.

Quick note on security:

While you mentioned using * as a wildcard origin, it's worth keeping the specific capacitor://localhost origin if possible, especially if you're using authentication tokens with the "Allow credentials" option enabled. The CLI approach gives you that precision without compromising security.

I am looking into this 🙂
So the team has answered and here is our solution:you can add the CORS via Sanity CLI:
sanity cors add <capacitor://localhost>
We might add the functionality in
sanity.io/manage but that’s low on the list, bc we have a solution at hand 🙂
I just added * for now which works but is a bit less safe, but our API is read-only anyway. I just wanted to make sure it got added to your ticket system. Thank you 🙂

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?