A page can request data from a server at another origin, but browser JavaScript cannot necessarily read the response. Cross-origin resource sharing, or CORS, is a protocol by which the server can tell a browser which cross-origin responses it may expose to a requesting page. It is easiest to understand by separating three questions: was a request sent, did the server perform an operation, and may the calling JavaScript read the response?
The protocol messages and code below are teaching examples that use the reserved hostname example.test; they do not describe the technology stack of any particular service.
1. Identify the origin before tracing the request
An origin is the combination of scheme, host and port. For example, https://app.example.test and https://api.example.test have different origins because their hosts differ, even though they share a parent domain. Likewise, changing HTTPS to HTTP or changing the port changes the origin. A path or query change alone does not.
Definition 7.1.1
(Origin and CORS)
An origin is the combination of scheme, host and port. Cross-origin resource sharing (CORS) is the protocol by which a server, through response headers, states which other origins may read its responses. The browser applies that decision to web content and exposes a response to the calling script only if the headers allow it.
The same-origin policy restricts a page's access to cross-origin responses. CORS supplies a controlled exception: a server can return suitable response headers, and the browser checks them against the origin and credentials mode of the request. CORS is enforced by browsers for access by web content; it does not stop an arbitrary non-browser client from sending requests. The server still has to authenticate and authorize operations independently.
2. When does the browser send a preflight?
Before sending a cross-origin request, the browser classifies it. A request needs no preflight when all of the following hold: the method is GET, HEAD or POST; every header set by the script is CORS-safelisted (for example Accept, Accept-Language, Content-Language, Content-Type and a simple Range, subject to limits on their values); and a Content-Type, if present, is application/x-www-form-urlencoded, multipart/form-data or text/plain. A few further conditions concern upload event listeners and streamed bodies. Every other request is non-simple. That includes the methods PUT, PATCH and DELETE, any custom or Authorization header, and Content-Type: application/json.
Definition 7.1.2
(Preflight request)
A preflight request is an OPTIONS request that the browser sends by itself before a non-simple cross-origin request. It carries no credentials and not the page's request body. Access-Control-Request-Method names the intended method and Access-Control-Request-Headers lists the non-safelisted headers. Only if the response has a successful status and grants the origin, the method and every listed header does the browser send the actual request.
The server answers a preflight with Access-Control-Allow-Origin, Access-Control-Allow-Methods and Access-Control-Allow-Headers. It may add Access-Control-Max-Age so that the browser caches the permission for a number of seconds, up to a limit the browser chooses. A simple request skips this step, with a consequence developed in the section on failure at two stages: the server may perform a simple request's operation even though the response is later withheld from the script.
Common mistake
(Authenticating the preflight)
A server runs its login check before any CORS handling, so every request without a valid session receives 401. The browser sends the preflight without the page's cookies, so the preflight itself receives 401. A preflight needs a successful status, so the browser treats it as failed and never sends the actual request, even though that request, with its cookie, would have been accepted. Answer an OPTIONS request that carries Access-Control-Request-Method before the authentication step, and authenticate the actual request as usual.
3. A JSON submission and its preflight
Suppose a page at https://app.example.test sends a POST to https://api.example.test/notes. This example assumes that the server implements the contract shown below, the user has an eligible session cookie, and the page has obtained an application-specific CSRF token by an appropriate means. The token shown is illustrative. HTTPS, cookie eligibility and browser policy are part of the scenario; a cookie is not guaranteed merely because credentials: "include" appears in the code.
async function createNote(title, csrfToken) {
const response = await fetch("https://api.example.test/notes", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": csrfToken
},
body: JSON.stringify({ title })
});
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
return response.json();
}
Here application/json is not a CORS-safelisted request Content-Type, and X-CSRF-Token is not a safelisted request header. Assuming no applicable cached preflight permission, the browser first sends an OPTIONS preflight. Its request names the intended method and non-safelisted headers; it does not carry the actual JSON body or the token value. Browser preflight requests are sent without the request's cross-origin credentials. The following HTTP/1.1-style messages omit unrelated headers:
OPTIONS /notes HTTP/1.1
Host: api.example.test
Origin: https://app.example.test
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type, x-csrf-token
The server permits this combination with a successful response, for example:
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.test
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Content-Type, X-CSRF-Token
Vary: Origin
The allowed origin exactly matches the page's origin. The allowed method includes POST, and the allowed headers include both requested names; header names are case-insensitive. Access-Control-Allow-Credentials: true is needed here because the subsequent Fetch uses credentials mode include. A wildcard Access-Control-Allow-Origin: * cannot authorize access to a response for a request with credentials mode include. Vary: Origin is relevant when a server chooses its allowed origin based on the request's Origin, so a shared cache does not reuse one origin's response indiscriminately for another.
A successful preflight permits the browser to make the actual request; it is not the note creation itself. Under the stated cookie assumption, a simplified actual exchange is:
POST /notes HTTP/1.1
Host: api.example.test
Origin: https://app.example.test
Cookie: sid=example-session
Content-Type: application/json
X-CSRF-Token: example-token
{"title":"Graph notes"}
HTTP/1.1 201 Created
Access-Control-Allow-Origin: https://app.example.test
Access-Control-Allow-Credentials: true
Content-Type: application/json
Vary: Origin
{"id":42,"title":"Graph notes"}
The actual response also needs the appropriate CORS headers. Under this example's contract, 201 and the JSON body report the created note; response.ok is true and response.json() parses the body. Parsing can still fail if the body is malformed. For a non-success HTTP response whose CORS headers allow exposure, Fetch normally fulfills with a response, and the code explicitly throws after inspecting response.ok. A browser CORS failure instead appears to the script as a rejected Fetch; script code cannot inspect the blocked response's status or body.
4. Failure at two different stages
If the preflight fails its CORS check, and there is no cached permission allowing the request, the browser does not send this actual POST. Inspecting the server's OPTIONS response and the browser's network log helps locate that failure. By contrast, suppose the preflight succeeds, the browser sends the POST, the server creates the note, and the actual 201 omits Access-Control-Allow-Origin. The browser blocks the response from the script even though the operation may already have happened. A rejected Fetch is therefore not proof that a write did not occur. Retrying blindly may create a second note unless the application has a suitable server-side idempotency contract.
Margin Note
Debug CORS in three questions
Ask in order: was the request sent, did the server act, may the script read the response? Open the network log and look for the OPTIONS request first; its absence or failure tells you which question you are on.
A CORS permission is not authorization. The server must still check the session and whether that user may create the note. Nor does it replace a CSRF defense: for cookie-authenticated writes, the server must use protections appropriate to its deployment, such as validating a CSRF token along with a suitable cookie and origin policy. Some cross-origin requests can be sent without preflight, so merely denying CORS access to the response is not a general way to stop unwanted state changes.
Counterexample mode
A prefix test is not an origin allowlist
Claim: the check origin.startsWith("https://app.example.test") is enough to allowlist the application, and the server then echoes the matching Origin together with Access-Control-Allow-Credentials: true. Take a page served from https://app.example.test.evil.test. Its origin string begins with the allowed text, so the check passes and the server answers with Access-Control-Allow-Origin: https://app.example.test.evil.test. For a user whose browser sends the session cookie, the script of that page can now read the JSON response. The weaker test origin.includes("example.test") likewise admits https://example.test.evil.test. The repair is to compare the whole origin with a fixed set, as allowedOrigins.has(origin) does in the second worked example below: an origin is scheme, host and port taken as a unit, not a string prefix.
5. Which response headers a script can read
Even when a response is allowed, the script sees only the CORS-safelisted response headers by default: Cache-Control, Content-Language, Content-Length, Content-Type, Expires, Last-Modified and Pragma. A header such as X-Total-Count appears in the browser's developer tools, yet response.headers.get("X-Total-Count") returns null unless the server also sends Access-Control-Expose-Headers: X-Total-Count. Here too, what is visible on the network differs from what the script may read. An API that reports pagination or rate-limit information in custom headers must therefore list them explicitly, or browser scripts will never see them.
Common mistake
(Silencing the error with no-cors)
A developer meets a CORS error and adds mode: "no-cors" to the call. The fetch no longer rejects, but the response is opaque: its status is 0, its body is empty and no header can be read, so the script still learns nothing. The request is also restricted to simple methods and headers. The error is repaired by the server sending suitable CORS headers, not by the caller asking the browser to look away.
6. Worked examples
Worked example 7.1.3
(A public GET read with the wildcard origin)
A page at https://app.example.test runs the following with credentials omitted. Assume there is no redirect and that the server answers 200 with JSON and Access-Control-Allow-Origin: *.
const response = await fetch("https://api.example.test/public-notes", { credentials: "omit" });
const notes = await response.json();
GET /public-notes HTTP/1.1
Host: api.example.test
Origin: https://app.example.test
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type: application/json
[{"id":1,"title":"Public note"}]
The method is GET and the script sets no headers, so the request is simple: the browser sends it directly and adds the Origin header itself. The wildcard is acceptable because the credentials mode is omit. The browser therefore exposes the 200 response, and response.json() parses the array. No preflight was needed, and the response's Content-Type: application/json does not trigger one, because only request headers and methods matter for that decision. None of this makes the data secret, and a server that omitted the header would make the identical call fail in the browser.
Worked example 7.1.4
(A PUT whose preflight lists too few methods)
The page sends fetch("https://api.example.test/notes/42", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: "Renamed" }) }). The server's answer to the browser's preflight is shown below.
OPTIONS /notes/42 HTTP/1.1
Host: api.example.test
Origin: https://app.example.test
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: content-type
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.test
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type
Vary: Origin
PUT is not a safelisted method and application/json is not a safelisted content type, so the preflight was required. The browser compares the requested method PUT with Access-Control-Allow-Methods: GET, POST, finds it missing and treats the preflight as failed. The actual PUT is never sent, so the note is not renamed; the script's fetch rejects with a TypeError and can read neither a status nor a body. Only the OPTIONS request reached the server. The fix is on the server, which must list the method and the headers. The middleware below also adds the headers to every response from an allowed origin, because error responses without them would be blocked too:
import express from "express";
const app = express();
const allowedOrigins = new Set(["https://app.example.test"]);
app.use((req, res, next) => {
const origin = req.get("Origin");
if (origin && allowedOrigins.has(origin)) {
res.set("Access-Control-Allow-Origin", origin);
res.set("Access-Control-Allow-Credentials", "true");
res.append("Vary", "Origin");
}
if (req.method === "OPTIONS" && req.get("Access-Control-Request-Method")) {
res.set("Access-Control-Allow-Methods", "GET, POST, PUT");
res.set("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token");
res.set("Access-Control-Max-Age", "600");
return res.status(204).end();
}
next();
});
app.use(express.json());
For an origin that is not in the set the middleware sets no Access-Control-Allow-Origin header, so the browser blocks that page's access. These headers only inform browsers; the route handlers must still authenticate and authorize each request.
Worked example 7.1.5
(The write succeeded but the response is blocked)
The POST from the JSON-submission section passes its preflight, but the application's actual response is the following, with no CORS headers.
HTTP/1.1 201 Created
Content-Type: application/json
{"id":43,"title":"Graph notes"}
The browser delivered the request, so the server ran its handler and stored the note with id 43. When the response arrives, the browser finds no Access-Control-Allow-Origin that matches the page's origin and withholds the response. The script's await fetch(...) rejects with a TypeError and the code cannot inspect the 201. A user who sees an error and presses retry may create a second note. To recover, the server must add the CORS headers to actual responses, including error responses. A retry-safe design stores a client-generated request identifier, or provides a read endpoint, so that the client can find out what happened rather than assume the write failed.
7. Practice
Quick check
(Classify three requests)
For each cross-origin request, say whether a preflight precedes it. (a) fetch(url, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: "a=1" }). (b) fetch(url, { method: "PUT" }). (c) fetch(url, { headers: { "X-Request-Id": "r1" } }).
Solution
(a) No preflight: POST with only a form content type is a simple request. (b) A preflight is sent, because PUT is not a CORS-safelisted method even without headers or a body. (c) A preflight is sent: the method is GET, but X-Request-Id is not a safelisted header. Request (a) can reach the server and change state even if CORS later denies the script access to the response.
Quick check
(Wildcard with credentials)
A page calls fetch(url, { credentials: "include" }). The response has Access-Control-Allow-Origin: * and Access-Control-Allow-Credentials: true. Does the script get the response? How should the server respond instead?
Solution
No. When the credentials mode is include, a wildcard Access-Control-Allow-Origin does not authorize reading the response, and Access-Control-Allow-Credentials: true does not repair it. The browser blocks the response and fetch rejects. The server should compare the request's Origin with an allowlist, echo the matching origin exactly, keep Access-Control-Allow-Credentials: true, and add Vary: Origin so that caches keep the responses for different origins apart.
Quick check
(A header that disappears)
The developer tools show X-Total-Count: 57 on an allowed cross-origin response, but response.headers.get("X-Total-Count") returns null. Explain and fix.
Solution
A script may read only CORS-safelisted response headers unless the server exposes others. X-Total-Count is not on that list. The server must add Access-Control-Expose-Headers: X-Total-Count to the response; the script can then read the value. The header was never missing from the network traffic, only hidden from the script.
Quick check
(CORS as a security wall)
A developer says: "Our API sends CORS headers only for https://app.example.test, so no other site or program can call it." Give two reasons why this is wrong.
Solution
First, CORS is enforced by browsers on web content. A command-line client, a script on another server or a modified browser ignores it and can send any request. Second, even inside a browser a simple request is sent without a preflight, and CORS only decides whether the calling script may read the response, not whether the server processed the request. Protection therefore needs authentication, authorization and a CSRF defense on the server.
Quick check
(DELETE and a two-method preflight)
The preflight for DELETE /notes/42 returns 204 with the correct Access-Control-Allow-Origin and Access-Control-Allow-Methods: GET, POST. Which requests reach the server, what does the script observe, and what must change?
Solution
Only the OPTIONS preflight reaches the server. The browser sees that DELETE is not listed, treats the preflight as failed and never sends the DELETE, so the note still exists. The script observes a rejected fetch with no status or body. The server must add DELETE to Access-Control-Allow-Methods. This differs from the blocked 201 in the third worked example, where the write really happened.