Before blaming the backend for a CORS error: a cross-origin debugging guide for the frontend
Your frontend calls your own backend and gets a CORS error — but the request may never have gone out at all. This guide follows the MDN same-origin policy and CORS official docs: the origin triple, write/embed/read, simple requests and preflight, why the wildcard fails with credentials, plus a five-step debugging method and five anti-patterns.

First, the boundaries. This site already has a web security baseline guide covering CSP, CSRF, XSS, and SQL injection — that one is about "keeping attacks out," defense. This guide is about the opposite direction: your own frontend calling your own backend, and the browser blocking it anyway. There is also an API resilience guide about timeouts, retries, circuit breakers, and degradation, but its premise is "the request went out and the backend had a problem." This guide starts one step earlier — the request never went out at all, or it went out and came back, and the browser still will not let you read it. Both kinds of failure look like errors, but the fixes are completely different, and mixing them up costs an afternoon.
The "Cloud Flower Market" used below is a fictional practice project: a small online flower stall, with its frontend running on local port 5173 and its API on another domain. Every action, code snippet, and number built around it in this article was invented to explain the method. It is not a real record. All rules, header names, and behaviors for the same-origin policy and CORS come from MDN's official documentation on those two topics; the sources are in each article's meta information and evidence record. The foo.example and bar.other domains in the MDN examples are the documentation's own example domains, not real websites.
First, what an "origin" is: protocol, host, and port
When a browser decides whether two addresses are "one family," it looks at exactly three things: protocol, host, and port. All three must match to be same-origin; if any one differs, it is cross-origin. MDN's same-origin policy documentation uses http://store.company.com/dir/page.html as the baseline and gives a comparison table that is worth memorizing: changing only the path to dir2/other.html is still same-origin, because only the path differs; switching to https is cross-origin, because the protocol differs; switching to port 81 is cross-origin, because http defaults to port 80; switching to news.company.com is cross-origin, because the host differs. Subdomains do not count either — news and store may look like family, but to the browser they are two different homes.
This table is worth keeping in mind because the most common cross-origin setup in vibe coding is one you create yourself: the frontend dev server runs on localhost:5173 and the backend on localhost:3000. Same host, same protocol, different port — cross-origin. Another common case: local development uses http and production uses https, and a request that worked yesterday breaks today because one of the three changed. Check the triple first, and many "suddenly broken" cases explain themselves.
Two lesser-known traps are worth knowing. First, if you open a local HTML file directly with file://, modern browsers generally treat its origin as an "opaque origin" — files in the same folder do not count as same-origin, and you can still get CORS errors. Do not double-click files for local previews; start a local server first. Second, the old document.domain trick is deprecated, and MDN marks it with an explicit warning: it undermines the security protections of the same-origin policy and causes interoperability problems and security bugs. AI-generated legacy code sometimes still contains that line. Delete it when you see it; do not leave it in.
Write, embed, read: the browser only blocks "read"
The same-origin policy sorts cross-origin interaction into three kinds: writes, embeds, and reads. Cross-origin "writes" are usually allowed — clicking a link to another site, submitting a form to another domain, or a redirect. Cross-origin "embeds" are usually allowed too — pulling in third-party JavaScript with a script tag, third-party CSS with a link tag, showing another site's image with an img tag, playing another site's video, or embedding a page in an iframe. Cross-origin "reads" are usually not allowed: your JavaScript cannot directly read data returned from another site.
This distinction matters because it explains why "the image shows up but the API call fails." An image is embedded — the browser only displays it and does not let your JavaScript read its pixels. An API returning JSON is something your code needs to read, so the browser has to care. It also explains why a CORS error does not mean "the request was blocked" — most of the time the request really went out, the server answered normally, and the browser held the response back after receiving it, just before handing it to your code. Your backend log shows the request, the backend developer says "200 on my side, no problem," and the frontend still turns red. Neither side is lying; the gate is in the browser's hands.
So what is CORS actually for? MDN puts it plainly: CORS is a part of HTTP that lets servers say which other hosts a browser should permit to load content. It is not a back door in the browser; it is the server attaching a pass to its response: Access-Control-Allow-Origin. Without that pass, the browser does not hand the response over by default; with it, it does. The subject is always the server. All the frontend can do is "send the request by the rules" — it cannot change the pass.
Simple requests: the kind that needs no preflight
Some cross-origin requests go straight out without asking first. MDN calls them simple requests. A request only counts as simple if it meets all of these conditions at once: the method must be GET, HEAD, or POST; the only headers you may set manually are the CORS-safelisted ones — Accept, Accept-Language, Content-Language, Content-Type, and Range; Content-Type must be one of three values: application/x-www-form-urlencoded, multipart/form-data, or text/plain; with XMLHttpRequest, no listeners may be registered on the upload object; and no ReadableStream may be used in the request.
Walk through MDN's example and it becomes concrete. A page on foo.example wants JSON from bar.other, so it writes fetch("https://bar.other"). The request the browser sends carries Origin: https://foo.example, telling the server "this is who I am." The server answers 200 with Access-Control-Allow-Origin: * in the response, meaning "any origin may read this." To allow only one origin, replace the star with the specific origin: Access-Control-Allow-Origin: https://foo.example. The whole exchange is two headers — one question, one answer.
Two misunderstandings trip up beginners here. First, the star is not a master key: it only works for requests without credentials. Once a request carries a cookie or login information, the star stops working — the credentials section below covers that in detail. Second, do not add the Access-Control-Allow-Origin header manually in frontend code. It is a server response header; adding it on the frontend does nothing, and worse, the extra custom header turns a request that was simple into one that needs a preflight, making things worse.

Preflighted requests: the browser sends a letter of inquiry first
Whenever a request is "not simple," the browser does not send it directly. It first sends a letter of inquiry using the OPTIONS method, asking the server "I want to send it this way — will you accept it?" That inquiry is called a preflight request. When does a preflight happen? The method is not GET, HEAD, or POST — for example PUT or DELETE; the Content-Type is application/json — note that application/json is not among the three simple values above, so the most common frontend API call, POST with JSON, triggers a preflight by default; or a custom header is present, such as Authorization or an X-PINGOTHER header.
MDN's preflight example is worth reading through. foo.example wants to POST to bar.other with Content-Type text/xml plus a custom X-PINGOTHER header. The browser first sends OPTIONS with two headers: Access-Control-Request-Method: POST, telling the server "I will use POST next," and Access-Control-Request-Headers: content-type,x-pingother, telling the server "I will carry these two headers next." The server answers 204 with Access-Control-Allow-Origin: https://foo.example, Access-Control-Allow-Methods: POST, GET, OPTIONS, Access-Control-Allow-Headers: X-PINGOTHER, Content-Type, and Access-Control-Max-Age: 86400. That means: the method is fine, the headers are fine, and this answer stays valid for 86,400 seconds — 24 hours — so there is no need to ask again each time. Only then does the browser send the real POST, and the real POST no longer carries the two Access-Control-Request-* headers — those belong only to the letter of inquiry.
Three practical points about preflight. First, the default lifetime of a preflight answer is only 5 seconds. The server can extend it with Access-Control-Max-Age, but every browser has its own internal cap, so setting it huge does not make it last forever. Second, a preflight request never includes credentials — MDN states this explicitly. To let the "real request with credentials" go through, the server must write Access-Control-Allow-Credentials: true in its preflight response. Third, if the server redirects after a preflight, some browsers report an error outright. MDN's advice is to change the server so the preflight never meets a redirect, or to turn the request back into a simple one. In local development, the most common preflight failure is much simpler: the backend never handles the OPTIONS method at all — no CORS middleware is configured, OPTIONS returns 404, and the browser stops at the inquiry step without ever sending the real request.
Credentialed requests: the star stops working here
By default, cross-origin fetch and XMLHttpRequest calls do not send credentials — cookies and HTTP authentication information stay home. To send them, the frontend must say so explicitly: set credentials: "include" in fetch, or set withCredentials to true on XMLHttpRequest. The frontend saying so is not enough; the server must also agree by returning Access-Control-Allow-Credentials: true in its response, or the browser will throw the response away and never hand it to your code. Note the order: the request went out, the response came back, and the browser decided at the last step "you cannot see this."
Once credentials enter the picture, the star fails everywhere, and MDN uses four "must not" rules: when responding to a credentialed request, the server must not use the * wildcard for Access-Control-Allow-Origin — it must name an explicit origin; it must not use * for Access-Control-Allow-Headers — it must list explicit header names; it must not use * for Access-Control-Allow-Methods — it must list explicit method names; and it must not use * for Access-Control-Expose-Headers — it must list explicit header names. AI-generated backend code trips over this constantly: the frontend says it needs a cookie, the backend returns a star to save trouble, and the browser blocks it anyway, with the console adding "the wildcard must not be used for credentialed requests." The fix is not on the frontend: the backend must replace the star with the frontend's real origin and add Vary: Origin to the response — because the same endpoint answers different origins with different allow headers, caches must vary by origin, or site A's pass will be served from cache to site B.
There is one more layer no server controls: third-party cookie policy. Even if the server allows everything, the browser may refuse to send cookies at all because of its own third-party cookie settings, or refuse to save a Set-Cookie it receives. MDN notes that a Set-Cookie only takes effect when Allow-Origin names an explicit origin rather than the star, and that the cookie's SameSite attribute and each browser's default policy all have a say. So when "login works locally but not in production," do not only check the CORS configuration — also check what the browser thinks about third-party cookies.
Five debugging steps: in order, no random tries
The most painful thing about CORS errors is that JavaScript can only know "an error occurred." MDN says it plainly: for security reasons, the specifics of the error are not available to JavaScript, and the only way to see what specifically went wrong is the browser console. So step one is always to open the console and read the browser's own words, instead of guessing at your code. The console states clearly which kind it is: a missing allow header, a failed preflight, or a credentials-versus-wildcard conflict.
Step two is the Network panel. Find the red request and check whether an OPTIONS request precedes it. If there is an OPTIONS request and the OPTIONS itself is red, the problem is the preflight: either the backend does not handle OPTIONS, or Allow-Methods or Allow-Headers does not include the method or header you need. If there is no OPTIONS and the real request itself is red, the problem is at the simple-request layer: check whether the response carries Access-Control-Allow-Origin and whether its value is right. In a Chrome DevTools Network panel screenshot, a failed request is marked red; click into it and read the response headers, and the answer is usually right there.
Step three is to check three lists one by one: is your request really a simple request (method, headers, and Content-Type)? Does the server's allow set have all three pieces (origin, methods, headers)? And if credentials are involved, are all four "no star" rules respected? Ninety percent of problems live in these three lists, with no architecture change needed.
Step four is choosing the fix. The cleanest approach in local development is a same-origin proxy on the frontend dev server: the browser only talks to the same-origin frontend server, which forwards API requests to the backend, so from the browser's point of view everything is same-origin and the cross-origin problem never exists. In production, deploying frontend and backend under the same domain is best; if that is impossible, configure an allowlist on the backend that names only your own frontend domain. Never take the shortcut of launching the browser with --disable-web-security or installing a "turn off CORS" extension — that only removes the door on your own machine, users' browsers will still block the request, and it leaves your own browser defenseless.
Step five is a pre-launch checklist: in production, does Access-Control-Allow-Origin name only your own domains, with no leftover star? For endpoints that carry cookies, is Access-Control-Allow-Credentials: true set with an explicit origin? Is Vary: Origin present? Does OPTIONS return 204 instead of 404? Is the preflight cache time reasonable? The fictional flower-market project went through exactly these five checks before launch, and the first one caught a star left in the backend config from development convenience. Once it was replaced, the logged-in checkout endpoint finally worked.
What the three real errors look like: recognize them by the console's own words
Console errors all look cryptic, but there are really only three sentence patterns, and matching one tells you which side to fix. The first pattern is "no allow header": the console says there is no Access-Control-Allow-Origin header, or that its value does not include your origin. The meaning is direct: the server never allowed you in. The backend has no CORS middleware configured, or it is configured but only allows the production domain, or your local development origin is not on the allowlist — all of these produce this one. The fix is on the backend: add your frontend origin to the allowlist, or use a same-origin proxy during development.
The second pattern is "preflight failed": the console says the preflight response did not pass the check, or simply that the preflight failed. Look at the OPTIONS request in the Network panel: if it returns 404, the backend does not handle OPTIONS at all; if it returns 200 but Allow-Methods does not include the method you need, or Allow-Headers does not include the header you need, the allowlist is too narrow. The fictional flower-market project hit exactly this one during its first integration: the backend allowed GET and POST but forgot PUT, so every request to update a recipe died at the preflight and the real request was never sent once.
The third pattern is "credentials versus wildcard": the console says that for a credentialed request, Access-Control-Allow-Origin must not be the wildcard. This is the friendliest of the three, because it tells you the fix directly: replace the star with an explicit origin and add Access-Control-Allow-Credentials: true. There is also a variant: the response does carry an allow header, but the browser still blocks it, because the response has no Allow-Credentials while your request carries credentials: "include." Match the sentence to the pattern, and which side to fix and which line to change mostly stop being guesses.
Five anti-patterns
Anti-pattern one: the backend returns a star while the frontend sends cookies. The most common mismatched pair — each side written on its own, blocked when put together. Remember one iron rule: credentials mean no star, with no exceptions.
Anti-pattern two: adding Access-Control-Allow-* headers manually on the frontend. These are response headers, not request headers. Adding them on the frontend only makes the request more complicated and adds a preflight, solving nothing.
Anti-pattern three: dodging a preflight error by switching to text/plain. Changing Content-Type to a simple value does avoid the preflight, but the backend parsing the body as JSON will then fail — trading a clear error for a harder one to trace. Dodging a preflight is not a fix; it is hiding the problem.
Anti-pattern four: treating CORS as CSRF protection. CORS decides "does the browser let your JavaScript read the response," while CSRF defense stops "someone else sending requests as your user." MDN's same-origin policy documentation states it clearly: to prevent cross-origin writes, check an unguessable token. The two jobs are separate, and a well-configured CORS setup does not mean CSRF is handled.
Anti-pattern five: using a CORS proxy as a production solution. A public proxy can rescue you temporarily during development, but writing it into production code hands users' requests and cookies to a third party to forward — slow, unstable, and unsafe. In production, use the same domain or a backend allowlist of your own.
Checklist: run through it next time CORS turns red
After the error: what did the console actually say? Is there an OPTIONS request in the Network panel? Did the OPTIONS fail, or the real request? Have you checked the three lists one by one — the simple-request conditions, the three-piece allow set, and the four credentials rules? Does the backend log show the request at all — if it does, the block is in the browser; if it does not, the request died at the preflight.
While fixing it: use a same-origin proxy in local development; allowlist only your own domains on the backend; replace every star with an explicit value on credentialed endpoints and add Vary: Origin; make sure OPTIONS answers normally; and do not touch --disable-web-security.
Before shipping: is there any star left over from development in the production config? Is the preflight cache time reasonable? Test again in another browser with a cleared cache, to confirm the allow headers are not a stale cached answer. A CORS error looks scary, but taken apart it is only three things: who you are (Origin), who is let in (Allow-Origin), and whether credentials travel along. Check in that order, and most errors can be located within half an hour.
Comments (0)
Sources
Related articles
You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.
One page should stand up on a phone, a tablet, and a computer. This guide follows MDN's Responsive web design, Using media queries, and the viewport meta reference: fluid HTML, the viewport tag, fluid grids and max-width, images that never burst their container, media query syntax, breakpoints set by content, mobile first, responsive type, testing capability instead of width, and a pre-launch checklist.
Numbers in JavaScript are one type, Number, stored as 64-bit floats — which is why 0.1 + 0.2 is 0.30000000000000004. This guide follows MDN's Basic math in JavaScript, Math, and Number: one number type, float error, counting money in cents, converting strings, NaN and Infinity, safe integers, the four rounding methods, Math.random, the Math toolbox, and formatting for display.