Nothing puzzles frontend engineers faster than an API endpoint that works flawlessly in Postman or cURL, yet immediately fails in Chrome or Firefox with: Access to fetch at 'https://api.example.com/data' from origin 'https://app.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
To fix CORS cleanly without opening security holes (or wasting hours editing React fetch flags that cannot override server rules), you need to understand one core truth: CORS is enforced strictly by the web browser, controlled strictly by the backend server's HTTP response headers. This guide walks through the Same-Origin Policy, simple vs. preflight OPTIONS requests, cookie credentials rules, and production-ready configurations for Express, FastAPI, and Nginx.
- 1. What Is an "Origin" & Why the Same-Origin Policy Exists
- 2. Simple Requests vs. Preflighted
OPTIONSRequests - 3. The Core CORS Response Headers Explained
- 4. The Wildcard Trap: Why
*Fails With Cookies & Auth Headers - 5. Hidden Causes: Redirects, 502 Errors & Missing
Vary: Origin - 6. Safe Backend Configurations (Express, FastAPI, Nginx)
- 7. Local Development Proxies (Vite / Next.js) vs. Production
- 8. Step-by-Step CORS Debugging Workflow
1. What Is an "Origin" & Why the Same-Origin Policy Exists
A web origin consists of exactly three components: scheme (https), host (techcar.online), and port (443). If any of those three differs between the webpage making the JavaScript request and the API server receiving it, the request is cross-origin:
Target URL (from https://techcar.online) | Same-Origin? | Why? |
|---|---|---|
https://techcar.online/base64/ | Yes | Same scheme, host, and default port 443. |
https://api.techcar.online/v1/items | No | Different subdomain host (api.techcar.online). |
http://techcar.online/v1/items | No | Different scheme (http vs https). |
https://techcar.online:8443/v1/items | No | Different port (8443 vs 443). |
Why do browsers block cross-origin reads by default? Imagine you are logged into your online bank in Tab 1, and in Tab 2 you visit an untrusted blog. Without the Same-Origin Policy (SOP), JavaScript on that blog could silently call fetch("https://yourbank.example/api/balance", { credentials: "include" }) using your browser's active banking cookies and read your private balance! CORS (Cross-Origin Resource Sharing) lets servers explicitly opt in and declare which trusted origins are allowed to read responses.
2. Simple Requests vs. Preflighted OPTIONS Requests
Not every cross-origin request triggers a preflight check. Browsers classify requests into two flows:
- Simple Requests (No Preflight): Only
GET,HEAD, orPOSTrequests with basic headers (Accept,Accept-Language,Content-Language) andContent-Typelimited totext/plain,multipart/form-data, orapplication/x-www-form-urlencoded. Notice the browser sends the request directly, then checksAccess-Control-Allow-Originon the response before letting JavaScript read the body. - Preflighted Requests (
OPTIONSFirst): As soon as you sendContent-Type: application/json, attach anAuthorization: Bearer <jwt>header, add custom headers likeX-Request-Id, or use methods likePUT,PATCH, orDELETE, the browser pauses the real request and fires an automaticOPTIONSpreflight asking the server: "Is origin X allowed to send method Y with header Z?"
If the server fails to reply 204 No Content (or 200 OK) with the right Access-Control-Allow-* headers to that OPTIONS call, the browser aborts immediately and never sends the actual POST/PUT request.
3. The Core CORS Response Headers Explained
| Header | Example Value | Purpose |
|---|---|---|
Access-Control-Allow-Origin | https://techcar.online | Exact origin permitted to read the response (or * for public unauthenticated APIs). |
Access-Control-Allow-Methods | GET, POST, PUT, DELETE, OPTIONS | Methods permitted during preflight checks. |
Access-Control-Allow-Headers | Content-Type, Authorization | Non-simple request headers permitted (note: * does NOT cover Authorization in all browsers—list Authorization explicitly!). |
Access-Control-Allow-Credentials | true | Allows cookies, TLS client certs, or HTTP Auth when client sets credentials: "include". |
Access-Control-Max-Age | 86400 | Caches preflight OPTIONS result in seconds so browsers skip repeating preflights on every API call. |
Access-Control-Expose-Headers | X-Total-Count, Retry-After | Lets frontend JavaScript read custom response headers via res.headers.get(). |
4. The Wildcard Trap: Why * Fails With Cookies & Auth Headers
Two classic traps break developer setups even when CORS headers appear present:
Access-Control-Allow-Origin: *+Access-Control-Allow-Credentials: trueis illegal: Per the Fetch standard, browsers strictly reject wildcard*whenevercredentials: "include"(or AxioswithCredentials: true) is active. Your backend must check the incomingOriginheader against an allowlist and echo back that exact single origin (e.g.Access-Control-Allow-Origin: https://techcar.online).Access-Control-Allow-Headers: *does NOT always authorizeAuthorization: Always listAuthorization, Content-Typeexplicitly inAccess-Control-Allow-Headerson authenticated APIs.- Never blindly reflect arbitrary
Originheaders withAllow-Credentials: true: Settingres.setHeader("Access-Control-Allow-Origin", req.headers.origin)without checking an allowlist completely defeats the Same-Origin Policy and lets any malicious website steal authenticated user data!
5. Hidden Causes: Redirects, 502 Errors & Missing Vary: Origin
Sometimes your CORS middleware looks spotless, yet Chrome still reports a CORS error:
- Backend Crashed (500 / 502) Before CORS Middleware Ran: If Nginx returns a
502 Bad GatewayHTML error page because your Node process crashed, Nginx's default error page has noAccess-Control-Allow-Originheader—so Chrome reports a CORS error instead of showing the real 502 failure! Always inspect the actual HTTP status code in the Network tab. - HTTP-to-HTTPS or Trailing Slash Redirect During Preflight: Calling
http://when the server redirects tohttps://, or calling/userswhen Django redirects to/users/, fails preflight checks because browsers forbid redirects onOPTIONSpreflight requests! - CDN Cache Poisoning Without
Vary: Origin: If you dynamically echoAccess-Control-Allow-Originfor multiple allowed domains behind Cloudflare or CloudFront, you MUST sendVary: Origin—otherwise CDN caches may serveOrigin-A's cached header to requests fromOrigin-B!
6. Safe Backend Configurations (Express, FastAPI & Nginx)
Here are clean, allowlist-based CORS setups you can drop straight into production services:
// 1. Node.js / Express (using official "cors" package)
import cors from "cors";
const ALLOWED_ORIGINS = new Set([
"https://techcar.online",
"https://www.techcar.online",
"http://localhost:3000"
]);
app.use(cors({
origin(origin, callback) {
// Allow same-origin / server-to-server requests with no Origin header
if (!origin || ALLOWED_ORIGINS.has(origin)) {
return callback(null, true);
}
return callback(new Error("Origin not allowed by CORS"));
},
methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization"],
credentials: true,
maxAge: 86400
}));
# 2. Python / FastAPI
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://techcar.online", "http://localhost:5173"],
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["Content-Type", "Authorization"],
max_age=86400,
)
Remember auth middleware ordering: Register your CORS middleware before your authentication/JWT middleware! If an auth middleware rejects unauthenticated OPTIONS preflight requests with 401 Unauthorized (because browsers never send Authorization headers inside OPTIONS preflights!), every authenticated browser call will fail CORS.
7. Local Development Proxies vs. Production Same-Origin
Why use a "Disable Web Security" browser flag when you can solve CORS cleanly at the architecture level? During local development with Vite or Next.js, configuring a dev proxy forwards /api/* from http://localhost:5173/api to your backend server, making requests appear same-origin to the browser. Even better, in production, serving both your frontend and backend under the same origin (for example, https://techcar.online/ and https://techcar.online/api/ via Nginx/Cloudflare routing) eliminates preflight OPTIONS round-trips completely and improves API latency!
8. Step-by-Step CORS Debugging Workflow
- Open browser DevTools → Network tab and filter by
Fetch/XHR. - Look for both the
OPTIONSpreflight request and the main request, and check their actual HTTP status codes (watch out for301/302redirects or401/500/502before blaming headers). - Test the preflight directly from your terminal using cURL:
curl -i -X OPTIONS https://api.techcar.online/v1/orders \ -H "Origin: https://techcar.online" \ -H "Access-Control-Request-Method: POST" \ -H "Access-Control-Request-Headers: Content-Type, Authorization"
- Confirm the response returns
204or200, includesAccess-Control-Allow-Originmatching your exact origin, lists your requested method/headers, and includesVary: Origin.
9. Nginx & Reverse-Proxy CORS Configuration (With Error Pages)
Sometimes an API gateway or static server sits behind Nginx. A classic Nginx pitfall is forgetting the always parameter on add_header directives! Without always, Nginx drops all Access-Control-Allow-Origin headers whenever the backend returns 4xx or 5xx statuses—causing browsers to hide helpful 400 or 401 JSON messages behind generic CORS errors:
# Nginx location block with safe allowlist & "always" flag
set $cors_origin "";
if ($http_origin ~* "^https://(www\.)?techcar\.online$") {
set $cors_origin $http_origin;
}
location /api/ {
if ($request_method = "OPTIONS") {
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
add_header Access-Control-Allow-Headers "Authorization, Content-Type" always;
add_header Access-Control-Allow-Credentials "true" always;
add_header Access-Control-Max-Age 86400 always;
add_header Vary "Origin" always;
return 204;
}
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Access-Control-Allow-Credentials "true" always;
add_header Vary "Origin" always;
proxy_pass http://127.0.0.1:4000;
}
Double-Header Warning: Never configure CORS headers in both Nginx and Express/FastAPI at the same time! Sending two duplicate Access-Control-Allow-Origin headers causes Chrome to reject the response immediately with: The 'Access-Control-Allow-Origin' header contains multiple values 'https://techcar.online, https://techcar.online', but only one is allowed. Choose one layer (either your proxy or your application framework) to own CORS headers exclusively.
10. Why CORS Alone Is Not Full CSRF Protection
While CORS prevents external websites from reading responses from your API, remember that legacy "simple" POST requests (such as an HTML <form> submitting application/x-www-form-urlencoded) are still transmitted by browsers without a preflight! If your endpoints rely on cookies for authentication, always combine CORS allowlists with SameSite=Lax (or Strict) cookies, validate JSON Content-Type strictly on mutating endpoints, or enforce anti-CSRF tokens.
11. Reducing Preflight Latency With Access-Control-Max-Age
In high-traffic single-page applications making dozens of authenticated POST and PATCH calls per minute, sending a separate OPTIONS preflight request before every API call effectively doubles network latency on mobile connections. Setting Access-Control-Max-Age: 86400 (or 7200 depending on browser caps) instructs Chrome, Firefox, and Safari to cache preflight permissions locally so subsequent requests execute immediately with zero preflight round trips. Pair preflight caching with smart API Caching Headers and clean OAuth 2.0 & PKCE token flows so cross-origin SPAs stay both fast and secure.
Frequently Asked Questions
Why do Chrome extensions or Postman bypass CORS while my React app gets blocked?
CORS is a browser security boundary protecting logged-in web users inside normal tabs. CLI tools like cURL, backend servers, and Postman do not enforce the Same-Origin Policy because they do not automatically share your browser's banking/email session cookies.
Does setting mode: "no-cors" in fetch() fix CORS errors?
No! Passing mode: "no-cors" tells the browser to return an opaque response whose status code is 0 and whose JSON body is completely unreadable by JavaScript. It is meant only for fire-and-forget pings or service worker caching, never for reading JSON APIs.
Why does localhost:3000 to localhost:8080 count as cross-origin?
Because the port numbers differ (3000 vs 8080). Origin equality requires identical scheme, hostname, and port.
How do I check what headers or JWT claims are inside my cross-origin request?
Paste your Bearer token into our Offline JWT Decoder or parse query parameters using the URL Query Parser.