Sub topic 10
Cross-Origin Requests, CORS, and Cookies
This chapter assumes you already know how to call fetch(), set request options such as method and headers, and check response.ok. You should also be able to open the browser's network panel and look at request and response headers.
What Counts as Cross-Origin
An origin is the combination of scheme, host, and port. https://app.example.com and https://api.example.com have different hosts, so they are different origins. http://localhost:3000 and http://localhost:8080 are also different origins, because their ports differ.
Browsers apply the same-origin policy. Page scripts may send requests to other origins, but they may not read the responses unless the other server allows it. CORS (Cross-Origin Resource Sharing) is the set of HTTP headers a server uses to grant that permission.
The browser enforces CORS, and the server only declares its rules. Tools like curl or Node.js ignore CORS completely, so a request that works in a terminal can still fail in a page.
Simple Requests and Preflights
Some requests are sent straight away. These are called simple requests: a GET, HEAD, or POST with only basic headers and a Content-Type of text/plain, multipart/form-data, or application/x-www-form-urlencoded. The browser sends the request, then checks the response for Access-Control-Allow-Origin before handing it to your code.
Other requests get a preflight first. Sending JSON with Content-Type: application/json, using PUT or DELETE, or adding a header like Authorization all trigger one. In a preflight, the browser sends an OPTIONS request to ask whether the real request is allowed.
The mode Option
The mode option controls how fetch handles cross-origin requests.
| mode | Behavior |
|---|---|
| `cors` (default) | Cross-origin requests allowed; response readable only if CORS headers permit it |
| `same-origin` | Rejects any cross-origin request with a `TypeError` |
| `no-cors` | Sends the request but returns an opaque response you cannot read |
The credentials Option
Credentials here means cookies, HTTP authentication, and TLS client certificates. The credentials option decides when they are sent:
omit: never send them.same-origin(default): send them only to the page's own origin.include: send them to every origin, including cross-origin APIs.
const response = await fetch('https://api.example.com/profile', {
method: 'PUT',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ displayName: 'Ada' })
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
console.log(await response.json());When you use credentials: 'include', the server's requirements get stricter. It must reply with:
Access-Control-Allow-Credentials: trueAccess-Control-Allow-Originset to the exact origin, such ashttps://app.example.com. A wildcard*is rejected.
The same rule applies to the preflight response. Cookies also have rules of their own: a cookie with SameSite=Lax or SameSite=Strict is not sent on a cross-site fetch. Cross-site cookies need SameSite=None; Secure.
Diagnosing CORS Failures
A blocked CORS request rejects with a plain TypeError such as "Failed to fetch". In JavaScript, this looks the same as a network outage. The browser hides the details from your code on purpose, so the real reason appears only in the console and the network panel.
| Console symptom | Likely cause |
|---|---|
| No `Access-Control-Allow-Origin` header | Server has no CORS setup for this route or origin |
| Wildcard `*` not allowed with credentials | Using `credentials: 'include'` while the server sends `*` |
| Header not allowed by `Access-Control-Allow-Headers` | Preflight doesn't list a header you sent, such as `Authorization` |
| Preflight returned 404 or 405 | Server doesn't handle `OPTIONS` |
Every fix in this table is on the server. Client-side code cannot grant itself permission. During development, a common workaround is to route requests through a proxy on your own origin, such as your dev server's proxy setting.
Exercise
A page at https://app.example.com calls fetch('https://api.example.com/cart', { credentials: 'include' }). The server responds 200 with Access-Control-Allow-Origin: * and Access-Control-Allow-Credentials: true, yet the fetch rejects with a TypeError. Why, and how should the server change its response?
Show answer
Credentialed requests may not use the wildcard origin. The server must echo the specific origin, Access-Control-Allow-Origin: https://app.example.com (usually with Vary: Origin), while keeping Access-Control-Allow-Credentials: true.
Exercise
Which of these requests from a different origin triggers a preflight: (a) GET with no custom headers, (b) POST with Content-Type: application/json, (c) DELETE?
Show answer
(b) and (c). The JSON Content-Type is not one of the simple content types, and DELETE is not a simple method. (a) is a simple request and is sent without a preflight.