Web Development

How CORS Works: Same-Origin Policy, Preflight Requests and Credentials

Why the browser blocks your API call, what the preflight is asking, and how to open access without opening a security hole

Zarton EditorsNov 7, 2026 · 7 min read
Listen to this article

Few error messages have frustrated more web developers than the one that starts "blocked by CORS policy." Your API works in Postman, works with curl, and then fails the moment your own front end calls it. The server is not broken, and the browser is not being difficult for fun. It is enforcing one of the web's oldest safety rules.

This guide explains how CORS works: the same-origin policy it relaxes, the difference between simple and preflighted requests, the response headers that grant access, how cookies change the rules, and the misconfigurations that turn a convenience into a security hole.

First, the same-origin policy

An origin is the combination of three parts of a URL: the scheme, the host and the port. Two URLs share an origin only when all three match. MDN's reference examples make the rule concrete. Compared with http://store.company.com/dir/page.html:

URLSame origin?Why
http://store.company.com/dir2/other.htmlYesOnly the path differs
https://store.company.com/page.htmlNoDifferent scheme
http://store.company.com:81/dir/page.htmlNoDifferent port
http://news.company.com/dir/page.htmlNoDifferent host

The same-origin policy stops a script loaded from one origin from reading responses from another. Without it, any page you visited could quietly fetch your webmail or your company intranet using your signed-in session and send the contents somewhere else.

The policy is narrower than many people assume. MDN groups cross-origin activity into three buckets:

  • Embedding is generally allowed. Images, stylesheets, scripts, video and iframes from other origins load fine.
  • Writes are generally allowed. Links, redirects and form submissions can reach other origins.
  • Reads are generally blocked. A script cannot inspect the body of a cross-origin response unless the server says it may.

That last bucket is where CORS comes in.

How CORS works: the server opts in

Cross-Origin Resource Sharing is a set of HTTP headers that lets a server tell the browser which other origins may read its responses. The browser always sends an Origin header describing where the calling page came from. The server answers with Access-Control-Allow-Origin, naming that origin or using * for anyone. If the answer does not match, the browser withholds the response from your JavaScript.

Two details explain most of the confusion. First, CORS is enforced by the browser, not the server, which is why curl and Postman never complain. Second, JavaScript is deliberately not told why a CORS check failed; the specifics appear only in the developer console. If fetch() rejects with a vague network error, open the console before anything else.

Simple requests

Some requests go straight to the server with no warm-up. MDN calls these simple requests, and a request qualifies only when all of the following hold:

  • The method is GET, HEAD or POST.
  • Only safelisted headers are set by hand, such as Accept, Accept-Language, Content-Language and a restricted Content-Type.
  • Content-Type, if present, is application/x-www-form-urlencoded, multipart/form-data or text/plain.

These rules mirror what an ordinary HTML form could already send, so allowing them adds no new risk. The server still has to return Access-Control-Allow-Origin before the page can read the reply.

Preflighted requests

Everything else triggers a preflight: before the real request, the browser sends an OPTIONS request asking permission. Sending JSON with Content-Type: application/json, adding an Authorization header, or using PUT or DELETE all qualify, which is why most modern API calls are preflighted.

# 1. Browser asks first
OPTIONS /api/orders HTTP/1.1
Origin: https://app.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: authorization, content-type

# 2. Server grants permission
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Max-Age: 600
Vary: Origin

# 3. Only now does the real PUT request go out
A preflight exchange. If step 2 is missing or does not match, step 3 never happens.

A common bug follows directly from this: the API's authentication middleware rejects the OPTIONS request because it carries no token. Preflights never include credentials, so they must be answered before auth checks run.

The CORS response headers at a glance

HeaderWhat it does
Access-Control-Allow-OriginOne allowed origin, or * for any origin on requests without credentials
Access-Control-Allow-MethodsMethods permitted for the real request (preflight responses)
Access-Control-Allow-HeadersRequest headers the real request may carry
Access-Control-Allow-Credentialstrue lets cookie- or auth-bearing requests read the response
Access-Control-Max-AgeSeconds the browser may cache the preflight result; browsers apply their own upper limit
Access-Control-Expose-HeadersExtra response headers JavaScript is allowed to read

If your server picks the allowed origin dynamically from an allowlist, also send Vary: Origin. That tells CDNs and other caches that the response differs by caller, so one origin's answer is not served to another. It is the same cache-key idea covered in our guide to HTTP caching with Cache-Control and ETags.

Cookies and credentials change the rules

By default, cross-origin fetch() calls do not send cookies or HTTP authentication. To include them, the page sets credentials: "include", and the server must reply with Access-Control-Allow-Credentials: true. Credentialed requests also forbid wildcards: the server has to name the exact origin, methods, headers and exposed headers instead of using *.

fetch("https://api.example.com/me", {
  credentials: "include"
});

// Server must answer with:
// Access-Control-Allow-Origin: https://app.example.com
// Access-Control-Allow-Credentials: true

Even then, cookies remain subject to the browser's third-party cookie rules and their SameSite setting, so a correct CORS setup can still arrive without the cookie you expected.

CORS misconfigurations that create real vulnerabilities

Because the error is so annoying, teams often "fix" CORS by loosening it until the message disappears. Security researchers at PortSwigger list the patterns that go wrong:

  1. Reflecting any origin. Copying the request's Origin straight into Access-Control-Allow-Origin while allowing credentials lets any website read a signed-in user's data.
  2. Sloppy allowlist matching. Checking that an origin merely starts or ends with your domain admits lookalike domains an attacker can register.
  3. Trusting the null origin. Browsers send null from sandboxed iframes and local files, and attackers can produce it on purpose.
  4. Trusting plain-HTTP subdomains. A network attacker who can tamper with an insecure origin inherits its access to your HTTPS API.
  5. Wildcards on internal services. An intranet tool that allows * can be read through an employee's browser from an outside page.

The safe pattern is an explicit allowlist compared by exact string match, and credentials enabled only where they are needed. Because an allowlist trusts hostnames, it also pays to understand how DNS turns those names into addresses before deciding which subdomains truly belong to you.

Key takeaways

  • An origin is scheme + host + port; change any one and the browser treats it as foreign.
  • The same-origin policy blocks cross-origin reads; CORS lets a server opt specific origins back in.
  • JSON bodies, custom headers and methods like PUT trigger an OPTIONS preflight that must succeed without credentials.
  • Credentialed requests need an exact origin and Access-Control-Allow-Credentials: true; wildcards are rejected.
  • Never reflect arbitrary origins or trust null, and remember CORS does not replace server-side security.

Frequently asked questions

Why does my API work in Postman but fail in the browser?

CORS is enforced only by browsers. Postman and curl do not apply the same-origin policy, so they show the response even when the server sends no CORS headers.

Can I fix CORS errors from the front end?

Not reliably. The server must send the right headers. During development you can route calls through a proxy on your own origin, but production APIs need correct server configuration.

Is Access-Control-Allow-Origin: * safe?

It is reasonable for truly public, non-credentialed data such as an open dataset or public fonts. It is risky on internal services and cannot be used with cookies or HTTP authentication.

Why is my preflight request failing with 401 or 404?

Preflights are OPTIONS requests without credentials. If your router has no OPTIONS handler or your auth layer runs first, the preflight fails. Answer OPTIONS before authentication.

Sources

Comments

No comments yet — be the first to share your thoughts.

Join the discussion

Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Keep reading

All posts

Run your whole business from one conversation.

Get startedTalk to us