Quick Takeaways
- CORS is enforced exclusively by web browsers under the Same-Origin Policy: a public REST endpoint that succeeds in curl or Postman will still fail with TypeError: Failed to fetch in browser JavaScript whenever Access-Control-Allow-Origin is missing or mismatched.
- Setting mode: 'no-cors' never fixes JSON fetching—it returns an opaque response with status 0 and an unreadable body. Real solutions require either an upstream CORS-enabled API or a same-origin edge proxy.
- Adding a single unnecessary header such as Content-Type: application/json or X-Requested-With on a GET request upgrades a simple fetch into a two-trip OPTIONS preflight, doubling round-trip latency and hitting Safari's 600-second preflight cache ceiling.
- Browsers block JavaScript from setting forbidden request headers (including User-Agent, Origin, and Referer) and hide non-safelisted response headers (such as X-RateLimit-Remaining and Retry-After) unless the server lists them in Access-Control-Expose-Headers.
- In a worked 12,000-DAU SEC filings and market screener case study (180,000 lookups/day), routing calls through a 30-line same-origin Cloudflare Workers edge cache removes 100% of CORS blocks and OPTIONS preflights, cuts upstream calls by 97.63% (down to 4,260/day), lowers P50 latency from 220 ms to 28 ms, and runs for $5/month.
1. Why curl Works While Browser fetch() Fails: Same-Origin Policy & CORS
Every frontend developer hits the same confusing moment when wiring a public REST API: copying the exact URL into curl, HTTPie, or a Node.js script returns crisp 200 OK JSON in 90 milliseconds, yet pasting that identical URL into browser fetch() inside a React or Vue component throws a red CORS console error and an opaque TypeError: Failed to fetch. Nothing is broken on the remote API server—the block happens inside your user's browser.
Web browsers enforce the Same-Origin Policy (SOP) so that an untrusted website open in Tab A cannot silently read authenticated JSON responses from your bank, corporate intranet, or cloud console open in Tab B using your stored cookies. Two URLs share an origin only when all three components match identically: scheme (https), host (api.example.com), and port (443). Calling https://api.frankfurter.dev from https://app.yoursite.com is therefore cross-origin.
Cross-Origin Resource Sharing (CORS), standardized in the WHATWG Fetch specification, is the opt-in protocol allowing an API server to tell browsers which external origins may read its response body. On every cross-origin fetch, the browser automatically attaches an Origin header (for example, Origin: https://app.yoursite.com). The remote server must reply with Access-Control-Allow-Origin: * (for public unauthenticated APIs) or echo the exact requesting origin. Notice two critical edge cases: first, if your fetch uses credentials: 'include' to send cookies or HTTP auth, wildcard '*' is strictly rejected—the server must echo the exact origin AND return Access-Control-Allow-Credentials: true. Second, setting mode: 'no-cors' only suppresses the console error by stripping JS read access to headers and body (returning response.type === 'opaque' and response.status === 0); it is useless for reading JSON payloads.
2. Simple Requests vs OPTIONS Preflight: How One Extra Header Doubles Latency
Even when a public API fully supports CORS, sloppy fetch() configuration silently triggers an extra HTTP OPTIONS preflight request before the browser ever sends your real GET or POST call. Under the Fetch Standard, a cross-origin request avoids preflight—remaining a 'simple request'—only if it meets every single restriction simultaneously: the method must be GET, HEAD, or POST; only CORS-safelisted request headers may be set manually (Accept, Accept-Language, Content-Language, Range, and Content-Type); and Content-Type is restricted exclusively to application/x-www-form-urlencoded, multipart/form-data, or text/plain.
The single most common frontend performance mistake on public REST APIs is attaching headers: { 'Content-Type': 'application/json' } to a GET request, or using a shared HTTP wrapper (such as an Axios instance configured with default JSON and Authorization headers) to call a zero-auth public endpoint. A GET request has no request body, so Content-Type: application/json serves zero purpose—yet because application/json is NOT a safelisted Content-Type, the browser pauses your fetch, sends an OPTIONS preflight with Access-Control-Request-Headers: content-type, waits one full network round-trip (RTT), and only then dispatches the GET. Worse, several zero-auth public APIs return Access-Control-Allow-Origin: * on GET but reject OPTIONS with 403 or 405 Method Not Allowed, causing an otherwise healthy CORS API to fail completely.
Browser preflight caching via Access-Control-Max-Age also has strict upper caps that differ by engine, regardless of how large a number the server sends. Chromium-based browsers (Chrome, Edge, Brave) cap cached preflights at 7,200 seconds (2 hours), Firefox caps them at 86,400 seconds (24 hours), and Safari/WebKit caps them at just 600 seconds (10 minutes). Because preflight cache entries are keyed per exact full URL including query parameters, every unique ?city=Tokyo or ?symbol=AAPL query string misses Safari's preflight cache and pays a brand-new OPTIONS round-trip unless you keep the request simple or route through a same-origin edge proxy.
| Request Property | Stays Simple (0 Preflight) | Triggers OPTIONS Preflight | Latency Impact (90 ms RTT) | Recommended Frontend Fix |
|---|---|---|---|---|
| HTTP Method | GET, HEAD, POST | PUT, PATCH, DELETE | +90 ms (2x RTT) | Use GET for reads; proxy writes same-origin |
| Content-Type Header | Omitted, or text/plain / form | application/json on GET or POST | +90 ms (+405 risk on GET) | Delete Content-Type on GET requests |
| Auth / API Key Headers | None (or query param if public) | Authorization, X-Api-Key, X-Token | +90 ms + leaks secret | Move API key to same-origin edge proxy |
| Cache Control Overrides | Use fetch({ cache: 'default' }) | Manual Cache-Control / Pragma header | +90 ms per unique URL | Avoid manual Cache-Control request headers |
| Custom Tracking Headers | None | X-Requested-With, X-Client-Version | +90 ms on every new query | Strip custom headers from public API client |
| Accept Header Value | Standard MIME (<= 128 bytes) | Value > 128 bytes or unsafe chars | +90 ms | Use Accept: application/json or default */* |
3. Forbidden Browser Headers, Non-CORS APIs & Hidden Rate-Limit Headers
CORS is not the only browser sandbox restriction affecting public REST APIs. The Fetch Standard defines a list of 'forbidden request-header names' that browser JavaScript is silently prevented from modifying or setting—most notably User-Agent, Origin, Referer, Host, Connection, and any header prefixed with Sec- or Proxy-. If your frontend code executes fetch(url, { headers: { 'User-Agent': 'MyApp/1.0 contact@myapp.com' } }), modern browsers silently ignore the override and transmit the standard browser User-Agent.
This single rule directly breaks or degrades several major zero-auth public APIs when called from browser JS. SEC EDGAR Company Facts (cors: no) requires both a non-browser origin path and a strict custom User-Agent containing an organization name and email address—blocking browser fetch on two independent fronts. Deezer Public Music Search also omits CORS headers completely (cors: no). Meanwhile, OpenStreetMap Nominatim and MusicBrainz explicitly require an identifiable application User-Agent to qualify for their 1 req/sec fair-use pools, meaning browser-direct requests fall into generic browser traffic buckets with higher rejection risk.
On the response side, browsers enforce a parallel visibility filter: even when a cross-origin request succeeds with HTTP 200, JavaScript calling response.headers.get(...) can read only seven CORS-safelisted response headers—Cache-Control, Content-Language, Content-Length, Content-Type, Expires, Last-Modified, and Pragma. Crucial operational headers like ETag, Retry-After, X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset return null in browser JS unless the remote API explicitly lists them inside Access-Control-Expose-Headers. When your frontend needs reliable rate-limit telemetry or ETag conditional caching on an API that does not expose those headers, a same-origin proxy restores 100% header visibility immediately.
| HTTP Response Header | Protocol Role | Wildcard '*' Valid? | Readable in Browser JS? | Common Production Pitfall |
|---|---|---|---|---|
| Access-Control-Allow-Origin | Authorizes requesting origin | Yes (without credentials) | No (browser internal) | Missing Vary: Origin when echoing dynamic origin |
| Access-Control-Allow-Methods | Lists methods valid for preflight | Yes (without credentials) | No (browser internal) | Omitting OPTIONS or PATCH breaks non-GET flows |
| Access-Control-Allow-Headers | Lists non-safelisted request headers | Yes (without credentials) | No (browser internal) | Must name Authorization explicitly even with * |
| Access-Control-Max-Age | Caches preflight result (seconds) | N/A (numeric seconds) | No (browser internal) | Safari ignores values > 600s; Chrome caps at 7,200s |
| Access-Control-Expose-Headers | Unlocks custom headers for JS | Yes (without credentials) | Unlocks listed headers | Without it, X-RateLimit-Remaining & ETag read null |
| Access-Control-Allow-Credentials | Allows cookies / auth headers | No (must be exact 'true') | No (browser internal) | Fails immediately if Allow-Origin is '*' |
4. Comparing 4 Browser-to-Public-API Architectures
Selecting the right architecture for a public REST API comes down to four operational questions: Does the upstream emit CORS headers? Does it require an API key or custom User-Agent? Do many users request the same keys? And how fresh must the data be? Matching your workload to one of four standard integration patterns eliminates unnecessary backend infrastructure while preventing sudden rate-limit outages.
Direct Browser Fetch works cleanly for zero-auth, CORS-enabled endpoints with user-specific or low-volume queries—such as live browser JSON playgrounds, ipify IP detection, or DiceBear SVG avatars. Because every visitor uses their own residential or mobile IP address, direct browser requests distribute per-IP rate limits organically across users. The drawback is zero cross-user cache sharing: if 10,000 users open a page displaying EUR/USD rates, direct fetch fires 10,000 duplicate calls to the upstream server.
A Same-Origin Edge Caching Proxy (deployed on Cloudflare Workers, Fastly Compute, or Vercel Edge under /api/proxy/* on your own domain) is the sweet spot for almost every production web app using public APIs. Because requests hit your own origin, browsers perform zero CORS checks and zero OPTIONS preflights. You can inject secret free API keys and compliant User-Agent headers safely on the server side, normalize query parameters, and share cached responses across tens of thousands of visitors from regional edge PoPs at 20–35 ms latency. A Backend-for-Frontend (BFF) route on a traditional origin server offers the same security but adds higher origin round-trip latency and server scaling cost. Finally, Build-Time Static Snapshots (SSG/ISR) are unbeatable for slowly changing reference catalogs like countries, public holidays, or museum indices, reducing runtime external dependencies to zero.
| Architecture Pattern | Browser Preflights | Secret Key & User-Agent | Cross-User Cache | Works on Non-CORS APIs | Typical P50 Latency | Monthly Infra Cost |
|---|---|---|---|---|---|---|
| 1. Direct Browser Fetch | 0 (simple) or 1M (preflight) | No (exposed / blocked) | None (per-browser only) | No | 140–280 ms | $0 |
| 2. Same-Origin Edge Cache Proxy | 0 (same origin) | Yes (server-side) | Yes (global PoP / shield) | Yes | 20–38 ms (hit) | $0–$5 / mo |
| 3. Origin BFF API Route (Node/Go) | 0 (same origin) | Yes (server-side) | Yes (Redis / in-memory) | Yes | 75–160 ms | $12–$35 / mo |
| 4. Build-Time SSG / Scheduled JSON | 0 (static CDN asset) | Yes (at build/cron time) | 100% CDN edge static | Yes | 12–25 ms | $0–$2 / mo |
5. Building a Safe 30-Line Edge Caching Proxy & Measuring Latency Gains
A production edge proxy should never be a generic ?url=https://... open forwarder—open proxies are rapidly discovered by automated scanners and abused for SSRF attacks against internal cloud metadata endpoints or third-party scraping under your IP reputation. Instead, map explicit, fixed route prefixes to an allowlist of upstream hosts and validated path templates: for example, /api/fx/latest maps strictly to https://api.frankfurter.dev/v1/latest with validated 3-letter currency codes, and /api/sec/cik/:id validates a 10-digit numeric CIK before calling data.sec.gov.
Five concise implementation rules maximize cache efficiency and safety in under 30 lines of edge TypeScript. First, canonicalize the cache key by lowercasing parameter names, sorting query parameters alphabetically, stripping tracking parameters (utm_*, fbclid), and rounding GPS coordinates to 2 decimal places (~1.1 km) so functionally identical queries share one cached entry. Second, strip incoming browser Cookie and Authorization headers before forwarding upstream so user sessions never leak to third parties and never accidentally bypass shared edge caches. Third, inject your server-side API key and a compliant User-Agent (e.g., RestAtlasProxy/1.0 contact@yourdomain.com) on the outbound request.
Fourth, set clean downstream Cache-Control headers combining a short browser TTL with a longer shared edge TTL and background refresh—such as Cache-Control: public, max-age=60, s-maxage=300, stale-while-revalidate=600, stale-if-error=3600—and return Vary: Accept-Encoding so gzip/brotli variants store cleanly. Fifth, enforce a strict AbortSignal.timeout(4000) on the upstream fetch and return clean JSON error envelopes rather than forwarding raw HTML gateway pages from a struggling public API. Table 4 quantifies the combined latency and wire-transfer improvement for a typical 14 KB JSON response under a 100 ms user-to-origin RTT and 22 ms user-to-edge RTT.
| Fetch Configuration | Network Round-Trips | Median End-User Latency | Origin Requests per 10,000 Views | Origin Bandwidth per 10,000 Views |
|---|---|---|---|---|
| Direct CORS with preflight (JSON header on GET) | 2 (OPTIONS + GET) | 245 ms | 10,000 GET + 10,000 OPTIONS | 145.0 MB (incl. preflight headers) |
| Direct CORS simple GET (no preflight) | 1 (GET only) | 135 ms | 10,000 GET | 140.0 MB |
| Same-origin edge cache (95% hit, s-maxage=300s) | 1 (to nearest PoP) | 28 ms (hit) / 142 ms (miss) | 500 GET | 7.0 MB (95.0% cut) |
| Edge cache + SWR + ETag 304 (75% unchanged) | 1 (to nearest PoP) | 26 ms (hit & SWR) | 125 full 200 + 375 ETag 304 | 1.86 MB (98.7% cut) |
6. Worked Numeric Case Study: Migrating a 12,000-DAU SEC Filings & FX Screener
Consider a browser-based retail investment screener serving 12,000 daily active users (DAU). Each user runs an average of 15 ticker and currency lookups per session, generating 180,000 frontend API lookups per day (5,400,000 lookups per month). Lookups split into three upstream APIs: 60% call SEC EDGAR Company Facts JSON (108,000 lookups/day; cors: no; 10 req/sec limit; mandatory custom User-Agent), 25% call a free-key market quote endpoint (45,000 lookups/day; requires X-Api-Key header), and 15% call Frankfurter FX rates (27,000 lookups/day; cors: yes; ECB daily updates).
Baseline Direct-Browser Breakdown: Calling these endpoints directly from browser JavaScript immediately breaks the core product. All 108,000 daily SEC EDGAR calls fail 100% in browsers due to missing Access-Control-Allow-Origin headers and the browser's forbidden User-Agent restriction. The 45,000 keyed quote lookups expose the API key in DevTools Network panels and trigger roughly 30,000 uncached OPTIONS preflight round-trips per day across Safari and varied ticker URLs—adding 95 ms per preflight (47.5 cumulative minutes of daily user wait time). Meanwhile, 27,000 daily Frankfurter lookups succeed in browsers but hammer the community origin with identical EUR/USD conversions.
Post-Migration Same-Origin Edge Proxy Math: We deploy a 30-line Cloudflare Workers proxy under /api/market/* on the app's own origin with strict host allowlisting, server-side key/User-Agent injection, and canonical cache keys: (1) SEC EDGAR route (/api/market/sec/:cik): normalized to 400 actively researched tickers with s-maxage=7200s (2 hours, matching quarterly XBRL reporting cadence) across 4 active refresh windows/day + 200 long-tail tickers = 1,800 origin calls/day (98.33% hit ratio; average 0.021 req/sec—over 470x below SEC's 10 req/sec limit); (2) Keyed Quote route (/api/market/quote/:symbol): normalized to 120 tracked symbols with s-maxage=300s (5 minutes) over 8 active market hours (96 windows, averaging 25 active symbols touched per window) = 2,400 origin calls/day (94.67% hit ratio); (3) Frankfurter FX route (/api/market/fx/:base): 10 base currencies with s-maxage=14400s (4 hours, 6 windows/day) = 60 origin calls/day (99.78% hit ratio).
Final Operational & Cost Impact: Total upstream origin calls drop from 180,000/day to exactly 4,260/day (127,800/month)—a 97.63% overall cache hit ratio. Browser CORS failures drop from 108,000/day to 0, OPTIONS preflights drop from ~30,000/day to 0, secret API key exposure drops to 0, and median lookup latency falls from 220 ms to 28 ms on edge cache hits. Financially, all 5,400,000 monthly edge requests fit comfortably inside the $5/month Cloudflare Workers Paid tier (which includes 10,000,000 monthly requests with zero egress surcharges), leaving 4,600,000 requests/month of growth headroom at less than one-sixth the cost of running dedicated regional BFF containers.
7. High-Cost CORS Misconfigurations & Security Checklist
When building your own API endpoints or edge proxies, five misconfigurations account for the majority of production outages and security findings. First, never blindly reflect the incoming Origin header together with Access-Control-Allow-Credentials: true; doing so grants every malicious website on the internet full authenticated read access to your users' private sessions. Always validate against an exact allowlist of trusted origins.
Second, whenever you dynamically set Access-Control-Allow-Origin to a specific domain rather than '*', always include Vary: Origin in the response headers; without Vary: Origin, a shared CDN can serve a response stamped for https://app-a.com to a visitor on https://app-b.com, causing sporadic, hard-to-reproduce CORS failures. Third, never ship a public unauthenticated ?url= proxy endpoint—restrict routes to named upstream targets and validated parameter formats. Fourth, audit shared Axios or fetch wrappers so public GET helpers never attach Content-Type: application/json or private auth headers by default. Fifth, when you need browser JavaScript to inspect X-RateLimit-Remaining, ETag, or Retry-After from a cross-origin API you control, explicitly list them in Access-Control-Expose-Headers.
Frequently Asked Questions
Why does a public REST API work in curl and Postman, yet fail with a CORS error in Chrome?
Because curl, Postman, and server-side runtimes do not enforce the browser Same-Origin Policy. Web browsers inspect the server's Access-Control-Allow-Origin response header before exposing the body to page JavaScript. If the public API omits that header (like SEC EDGAR or Deezer), the HTTP response still arrives over the network, but Chrome blocks your script from reading it.
Can I bypass a browser CORS error by adding mode: 'no-cors' to fetch()?
No. Setting mode: 'no-cors' tells the browser to send the request without CORS headers and return an 'opaque' response whose status is 0 and whose body cannot be read by JavaScript. Calling response.json() on an opaque response always throws an error. To read JSON from a non-CORS API, call it through a same-origin edge proxy or backend route.
Why is my browser sending an OPTIONS request before every GET request to a public API?
Your fetch call includes a non-safelisted header—most often Content-Type: application/json, Authorization, X-Api-Key, Cache-Control, or X-Requested-With. Removing unnecessary headers from GET requests converts it back to a simple CORS request with zero OPTIONS round-trips.
Why does response.headers.get('X-RateLimit-Remaining') return null even though I can see it in Chrome DevTools?
Chrome DevTools shows raw network headers, but the Fetch Standard restricts JavaScript on cross-origin responses to 7 safelisted headers (such as Content-Type and Cache-Control). Unless the upstream API sends Access-Control-Expose-Headers: X-RateLimit-Remaining (or you proxy the call same-origin), JavaScript intentionally receives null.
How long do browsers actually cache CORS OPTIONS preflight responses?
Each engine caps Access-Control-Max-Age independently: Chromium browsers cap it at 7,200 seconds (2 hours), Firefox caps it at 86,400 seconds (24 hours), and Safari/WebKit caps it at 600 seconds (10 minutes). Even within those limits, the cache key includes the full URL and query string, so dynamic query parameters trigger fresh preflights frequently.
Why can't browser JavaScript set the custom User-Agent required by SEC EDGAR or Nominatim?
User-Agent is classified as a forbidden request-header name in the WHATWG Fetch Standard for security and anti-spoofing reasons. Browsers silently ignore attempts to set it from frontend JavaScript. Any API requiring a custom User-Agent with your app name and email must be called from a server-side runtime or edge worker.
Are public third-party CORS proxy websites safe to use in production apps?
Never use third-party public CORS proxies in production. They can log or alter your payloads, go offline without notice, get IP-banned by upstream APIs due to abusive neighbors, and violate privacy compliance. Deploying your own 30-line allowlisted edge proxy on Cloudflare Workers or Vercel Edge takes five minutes, costs $0–$5/month, and gives you full cache and security control.
Official Sources & References
- MDN Web Docs — Cross-Origin Resource Sharing (CORS) Guide
- WHATWG — Fetch Living Standard (CORS Protocol & Forbidden Headers)
- MDN Web Docs — Forbidden Request Header Glossary
- MDN Web Docs — Access-Control-Max-Age Browser Caps
- MDN Web Docs — Access-Control-Expose-Headers Reference
- Cloudflare Developers — Workers Cache API Documentation
- IETF RFC 9110 — HTTP Semantics