Thuta Learning
API Tutorial
AdvancedWeb DevelopmentIntermediate

CORS & HTTPS

API TutorialLesson 2635 min

What you'll walk away with

  • Define an origin and explain why the browser, not the server, enforces CORS
  • Tell whether a request is simple or needs a preflight, and read a preflight request and response
  • Write allowlist-based Access-Control-Allow-Origin echo logic together with Vary: Origin
  • Explain why credentials and a wildcard (*) cannot be combined and why an arbitrary Origin must never be reflected
  • Separate what CORS does from authentication, and know what HTTPS adds

Explain it simply

Explain it simply

Think of the browser as the security guard of the building where your web page lives. When the JavaScript on that page wants to talk to another building, such as another site's API, the guard asks that building, "do you accept visitors from my building?" Only if the answer comes back as headers saying yes does the guard let the page read the reply.

The guard exists to protect the user sitting at the browser. curl, Postman, Node and other servers have no such guard, so the rule never applies to them. That is why "it works in curl but fails in the browser" is the classic sign of a CORS problem.

Problem → Why → Solution

The problem: it works in curl but not in the browser

A frontend developer builds an app for https://app.example.com that calls https://api.example.com. It works fine in curl and Postman, but the browser console shows a red error saying the request was blocked by CORS policy. The Network tab also shows an OPTIONS request that nobody wrote.

The "fixes" people try next are usually wrong. Adding mode: "no-cors" silences the error but turns the response opaque, so the data can no longer be read. Putting Access-Control-Allow-Origin on the client's request does nothing either, because it is a header the server sends in its response.

app.js
// Running in the browser, on the page https://app.example.com
const res = await fetch("https://api.example.com/v1/items", {
  mode: "no-cors", // hides the error, and also hides the data
  headers: {
    "Access-Control-Allow-Origin": "*", // a RESPONSE header: meaningless on a request
    Authorization: "Bearer demo-token",
  },
});
console.log(res.type, res.status); // "opaque" 0 -> the body is unreadable

Why can't the client fix this?

Permission has to come from the server that owns the data, not from the page that asks for it, and a page cannot declare itself allowed. The real fixes are to make the API server send the right Access-Control-* response headers, or to route the call through your own backend with a same-origin proxy.

Core concept: origins, browser enforcement and preflight

An origin is scheme + host + port. https://app.example.com and https://api.example.com differ in host, so they are different origins; http:// versus https:// differ, and so do different ports. Under the browser's same-origin policy, a page's JavaScript may send a request to another origin but may not read the response until that server says it is allowed. CORS, Cross-Origin Resource Sharing, is the protocol for giving that permission through response headers.

The browser does this checking. It adds an Origin header to the request, the server answers with response headers, and the browser then decides whether to hand the response to JavaScript. The server may therefore have received and processed the request already; CORS only blocks reading the response. That is why CORS is not authentication: anyone can call your API from curl, so you still need token or session checks to protect it.

Not every request needs a preflight. A "simple" request (GET, HEAD or POST, with only safelisted headers such as Accept, and a Content-Type of form-urlencoded, multipart/form-data or text/plain) is sent directly and its response headers are checked afterwards. Everything else needs a preflight: PUT, PATCH, DELETE, an Authorization header, any custom header, and Content-Type: application/json. A preflight is an OPTIONS request the browser sends first, carrying Origin, Access-Control-Request-Method and Access-Control-Request-Headers. Only if the server answers 2xx with matching Allow headers does the real request go out.

The response side has a few firm rules. Access-Control-Allow-Origin holds a single origin, *, or null, never a list of origins. When credentials such as cookies are involved, * stops working: you must echo the exact origin and add Access-Control-Allow-Credentials: true. Echo the origin only after checking it against an allowlist, and add Vary: Origin so a shared cache cannot serve one origin's response to another. By default JavaScript sees only a few response headers, so headers such as Retry-After must be listed in Access-Control-Expose-Headers.

Mental model: the browser asks, the server answers
  1. Page sends request + Origin
  2. Preflight OPTIONS if not simple
  3. Server answers with Allow-* headers
  4. Browser allows or hides the response

The server grants permission and the browser enforces it.

General pattern: preflight and answer

text
# 1. Preflight, sent by the browser only for non-simple requests
OPTIONS /resource
Origin: <page origin>
Access-Control-Request-Method: <METHOD>
Access-Control-Request-Headers: <header, header>

# 2. Server answers 2xx, then the browser sends the real request
Access-Control-Allow-Origin: <that exact origin>
Access-Control-Allow-Methods: <METHOD, METHOD>
Access-Control-Allow-Headers: <header, header>
Vary: Origin

The top half is what the browser sends and the bottom half is what the server answers. Allow-Origin must match the incoming Origin exactly, Allow-Methods and Allow-Headers must cover what the preflight asked for, and Vary: Origin is there for caches.

Example: an allowlist and a preflight on a live server

CORS never blocks Node's fetch, so a browser block cannot be demonstrated here, but the server's side can be shown completely. Node's fetch lets us set the Origin header by hand, so we can imitate the requests a browser would send and read which headers the server returns. The server allowlists two origins.

Watch four things in the output. The preflight gets a 204 with the full set of Allow-* headers. An allowlisted origin is echoed back. evil.example gets no Allow-Origin, yet the server's handler still runs, and only the browser would withhold that response from JavaScript. A request without an Origin header, like curl's, is not subject to CORS at all.

cors-server.mjs
import http from "node:http";

const ALLOWED = new Set(["https://app.example.com", "https://admin.example.com"]);
let handled = 0;

function corsHeaders(origin) {
  if (!origin || !ALLOWED.has(origin)) return {};
  return { "Access-Control-Allow-Origin": origin };
}

const server = http.createServer((req, res) => {
  const cors = { ...corsHeaders(req.headers.origin), Vary: "Origin" };
  const wantsMethod = req.headers["access-control-request-method"];
  const isPreflight = req.method === "OPTIONS" && wantsMethod;

  if (isPreflight) {
    if (cors["Access-Control-Allow-Origin"]) {
      cors["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE";
      cors["Access-Control-Allow-Headers"] = "Authorization, Content-Type";
      cors["Access-Control-Max-Age"] = "600";
    }
    res.writeHead(204, cors).end();
    return;
  }

  handled += 1; // the handler runs no matter which origin asked
  res.writeHead(200, { ...cors, "Content-Type": "application/json" });
  res.end(JSON.stringify({ items: [] }));
});

await new Promise((resolve) => server.listen(0, resolve));
const url = "http://127.0.0.1:" + server.address().port + "/v1/items";
const APP = "https://app.example.com";
const EVIL = "https://evil.example";

async function show(label, options, names) {
  const res = await fetch(url, options);
  console.log(label);
  console.log("  status:", res.status);
  for (const name of names) {
    console.log("  " + name + ": " + (res.headers.get(name) ?? "(none)"));
  }
}

function postFrom(origin) {
  const headers = { "Content-Type": "application/json" };
  if (origin) headers.Origin = origin;
  return { method: "POST", headers, body: "{}" };
}

const preflight = {
  method: "OPTIONS",
  headers: {
    Origin: APP,
    "Access-Control-Request-Method": "POST",
    "Access-Control-Request-Headers": "authorization, content-type",
  },
};
const everything = [
  "access-control-allow-origin",
  "access-control-allow-methods",
  "access-control-allow-headers",
  "access-control-max-age",
  "vary",
];
const basic = ["access-control-allow-origin", "vary"];

await show("preflight from " + APP, preflight, everything);
await show("POST from " + APP, postFrom(APP), basic);
await show("POST from " + EVIL, postFrom(EVIL), basic);
await show("POST with no Origin header", postFrom(), basic);
console.log("handler ran", handled, "times");
server.close();

Code breakdown

  1. Allowlistconst ALLOWED = new Set(["https://app.example.com", "https://admin.example.com"]);

    Allowed origins are exact strings in a Set. Avoid wildcards or loose checks such as endsWith('example.com'), which also match look-alike domains like evil-example.com.

  2. Unknown originif (!origin || !ALLOWED.has(origin)) return {};

    A missing or unlisted origin gets no CORS headers at all. The browser finds no Allow-Origin and will not give the response to JavaScript.

  3. Echo, not wildcardreturn { "Access-Control-Allow-Origin": origin };

    It returns exactly the origin that asked, and only after the allowlist check, which keeps the same logic usable for credentialed requests.

  4. Detect a preflightconst isPreflight = req.method === "OPTIONS" && wantsMethod;

    Not every OPTIONS request is a preflight. It counts as one only when the Access-Control-Request-Method header is present.

  5. Cache the answercors["Access-Control-Max-Age"] = "600";

    The browser remembers the preflight answer for 600 seconds, so it does not send an OPTIONS before every request. Browsers apply their own upper limit, so you cannot cache for days.

  6. Handler still runshandled += 1;

    This line runs for the request from evil.example too, which is the proof that CORS does not protect the server itself.

You should see
preflight from https://app.example.com
  status: 204
  access-control-allow-origin: https://app.example.com
  access-control-allow-methods: GET, POST, PUT, DELETE
  access-control-allow-headers: Authorization, Content-Type
  access-control-max-age: 600
  vary: Origin
POST from https://app.example.com
  status: 200
  access-control-allow-origin: https://app.example.com
  vary: Origin
POST from https://evil.example
  status: 200
  access-control-allow-origin: (none)
  vary: Origin
POST with no Origin header
  status: 200
  access-control-allow-origin: (none)
  vary: Origin
handler ran 3 times

Telling simple requests from preflighted ones

What surprises developers most is that a plain JSON POST triggers a preflight, because Content-Type: application/json is not safelisted. The function below is a simplified copy of the Fetch standard's rule, leaving out some header limits; the real decision always belongs to the browser.

needs-preflight.mjs
const SIMPLE_METHODS = new Set(["GET", "HEAD", "POST"]);
const SAFE_HEADERS = new Set([
  "accept",
  "accept-language",
  "content-language",
  "content-type",
]);
const SAFE_TYPES = new Set([
  "application/x-www-form-urlencoded",
  "multipart/form-data",
  "text/plain",
]);

function needsPreflight(method, headers = {}) {
  if (!SIMPLE_METHODS.has(method)) return true;
  for (const [name, value] of Object.entries(headers)) {
    const lower = name.toLowerCase();
    if (!SAFE_HEADERS.has(lower)) return true;
    if (lower === "content-type") {
      const type = value.split(";")[0].trim();
      if (!SAFE_TYPES.has(type)) return true;
    }
  }
  return false;
}

const cases = [
  ["GET", {}],
  ["POST", { "Content-Type": "application/x-www-form-urlencoded" }],
  ["POST", { "Content-Type": "application/json" }],
  ["GET", { Authorization: "Bearer token" }],
  ["PUT", {}],
  ["GET", { "X-Request-Id": "abc" }],
];
for (const [method, headers] of cases) {
  const pairs = Object.entries(headers).map(([k, v]) => k + ": " + v);
  const shown = pairs.join(", ") || "(no headers)";
  const verdict = needsPreflight(method, headers) ? "preflight" : "simple";
  console.log(method.padEnd(5) + shown.padEnd(48) + verdict);
}
text
GET  (no headers)                                    simple
POST Content-Type: application/x-www-form-urlencoded simple
POST Content-Type: application/json                  preflight
GET  Authorization: Bearer token                     preflight
PUT  (no headers)                                    preflight
GET  X-Request-Id: abc                               preflight

You can try a preflight yourself with curl by imitating the OPTIONS request a browser would send and reading the server's answer. This is a good way to check the server, but it cannot reproduce the block itself; for that you need a real browser.

bash
curl -i -X OPTIONS https://api.example.com/v1/items \
  -H "Origin: https://app.example.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: authorization, content-type"
text
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Max-Age: 600
Vary: Origin

Credentials and wildcards: why you must not reflect

Requests that carry cookies use the user's logged-in session, so they are riskier. That is why browsers reject Access-Control-Allow-Origin: * on a credentialed request. The shortcut "then I will echo back whatever Origin arrives" sidesteps that protection: any website a signed-in user visits can call your API with their session and read the response.

reflect-vs-allowlist.mjs
const ALLOWED = new Set(["https://app.example.com", "https://admin.example.com"]);
const ACAO = "Access-Control-Allow-Origin";
const ACAC = "Access-Control-Allow-Credentials";

// Dangerous: echoes whatever Origin it is given, and allows cookies.
function reflectEverything(origin) {
  return { [ACAO]: origin, [ACAC]: "true" };
}

// Safe: echoes the origin only when it is on the allowlist.
function allowlisted(origin) {
  if (!ALLOWED.has(origin)) return {};
  return { [ACAO]: origin, [ACAC]: "true", Vary: "Origin" };
}

function describe(headers) {
  if (!headers[ACAO]) return "(no CORS headers)";
  return "allow-origin=" + headers[ACAO] + " credentials=" + headers[ACAC];
}

for (const origin of ["https://app.example.com", "https://evil.example"]) {
  console.log(origin);
  console.log("  reflect-everything:", describe(reflectEverything(origin)));
  console.log("  allowlist:         ", describe(allowlisted(origin)));
}
text
https://app.example.com
  reflect-everything: allow-origin=https://app.example.com credentials=true
  allowlist:          allow-origin=https://app.example.com credentials=true
https://evil.example
  reflect-everything: allow-origin=https://evil.example credentials=true
  allowlist:          (no CORS headers)

Limits of the header wildcard

Even Access-Control-Allow-Headers: * does not cover the Authorization header; it must be listed by name. On credentialed requests the wildcard is treated as a literal string, so write header names out explicitly.

Reading a CORS failure in the browser

Read the console message carefully; it usually names the header that was missing, though the wording differs between browsers, so read it in yours. In the Network tab, find the OPTIONS request and look at its status and response headers. If the preflight returns 401 or 404, the problem is that route, not a CORS header.

Server errors add confusion. If the API returns a 500 or 401 and that response lacks CORS headers, the browser hides the real status and body from JavaScript and shows only a network-style failure. It looks like a CORS error while the real cause is a different bug on the server. Sending CORS headers on error responses too is the best habit.

text
HTTP/1.1 429 Too Many Requests
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Expose-Headers: Retry-After, X-RateLimit-Remaining
Vary: Origin
Retry-After: 30
X-RateLimit-Remaining: 0

That response ties back to the rate-limit lesson. Without Expose-Headers, browser JavaScript cannot read Retry-After through response.headers.get(), so a retry loop receives null and falls back to the wrong delay.

What HTTPS adds

HTTPS is HTTP over TLS. It encrypts requests so the network cannot read them, detects tampering, and uses a certificate to check that the server is the real one. Because API keys and bearer tokens travel in headers, without HTTPS anyone on the same wifi can read them. HTTPS replaces neither CORS nor authorization, though; it secures the transport only.

MechanismWhat it protects
TLS certificateProves you reached the real host
EncryptionHides tokens and bodies from the network
Strict-Transport-SecurityTells browsers to always use HTTPS
Secure cookieNever sends the cookie over plain HTTP

Browsers block an HTTPS page from calling an http:// API as mixed content, with an exception for localhost during development. Never turn certificate checking off in production with curl -k or NODE_TLS_REJECT_UNAUTHORIZED=0, because that cancels the protection HTTPS provides.

In real projects

Where this shows up in real projects

Every framework has CORS middleware: the cors package for Express, django-cors-headers for Django, @CrossOrigin in Spring. The allowlist is read from environment configuration instead of being hard-coded, with production and staging kept separate. Allow http://localhost:3000 only in development and keep it out of production. If a gateway in front of your API also handles CORS, do it in exactly one place so it never disagrees with the origin server.

Write a test matrix: cross origin (allowed, disallowed, missing) with method, custom header and credentials, and assert which headers come back. Include one server-to-server call so you know requests without an Origin keep working. If your frontend dev server proxies /api to the backend, the browser sees a same-origin call and CORS is not needed at all. Call third-party APIs that use secret keys from your own backend rather than from the browser, because a key in browser code is visible to everyone.

Common mistakes

Common mistakes

1. Treating CORS as access control

"I restricted CORS, so the API is private" is wrong. curl, scripts and other servers ignore CORS and can still call the endpoint. Private data needs authentication and authorization no matter what the CORS settings say.

2. Mixing credentials with * or reflecting Origin

Sending Access-Control-Allow-Origin: * together with Allow-Credentials: true is rejected by the browser. Fixing that by echoing every incoming Origin is worse: any website can then read the user's session data. Check against an allowlist instead.

3. Auth middleware rejecting OPTIONS

A preflight does not carry the Authorization header, because the browser sends it without credentials. If a middleware that demands a token on every route answers OPTIONS with 401, the preflight fails and the real request is never sent. Handle CORS before authentication.

4. Adding CORS headers only to success responses

When error responses (401, 429, 500) lack CORS headers, JavaScript cannot see the status or body and cannot tell why a call failed. Forgetting Vary: Origin on top of that creates intermittent, cache-dependent failures. Add the headers to every response.

Best practices

Best practices

  • Allow only the origins, methods and headers you actually need; do not open everything.
  • List response headers the client must read, such as Retry-After, in Access-Control-Expose-Headers.
  • When possible, put the frontend and the API behind one same-origin proxy so CORS is not needed at all.

Mini challenge

Mini challenge: play the browser's preflight check

Act as the browser and write preflightVerdict(origin, request, response), which decides whether a preflight response lets the real request go out. Then run six scenarios and print the verdicts. This is a simplified model of the Fetch standard.

  • Return a "blocked" verdict when the preflight status is not 2xx
  • Block when Access-Control-Allow-Origin is missing, or is neither * nor the page origin
  • With credentials, reject * and require Allow-Credentials: true
  • The request method must appear in Allow-Methods and every request header in Allow-Headers
  • The verdict is "allowed" or "blocked: <reason>"
preflight-verdict.mjs
// You play the browser: does this preflight response let the real request go out?
// request:  { method, headers: ["Authorization", ...], credentials: true or false }
// response: { status, headers: { "access-control-allow-origin": "...", ... } }

function preflightVerdict(origin, request, response) {
  // TODO 1: the preflight status must be 2xx
  // TODO 2: Access-Control-Allow-Origin must be present
  // TODO 3: with credentials, "*" is invalid and Allow-Credentials must be "true"
  // TODO 4: the allowed origin must be "*" or exactly the page origin
  // TODO 5: the method must be listed in Access-Control-Allow-Methods
  // TODO 6: every request header must be listed in Access-Control-Allow-Headers
  // return "allowed" or "blocked: <reason>"
}

// TODO: build six scenarios (good, 401 on OPTIONS, wrong origin, missing PUT,
// missing Authorization, "*" with credentials) and print one line for each

Expected: Six lines are printed: full allowlist allowed auth blocks OPTIONS blocked: preflight returned 401 wrong origin blocked: origin https://app.example.com not allowed no PUT blocked: method PUT not allowed Authorization missing blocked: header Authorization not allowed * with cookies blocked: wildcard origin with credentials

Show hint

Split the Allow-Methods and Allow-Headers values on "," into trimmed, lowercased arrays. Run the checks in the order given with early returns, so the first failing check is the reported reason.

Show solution
preflight-verdict.mjs
function preflightVerdict(origin, request, response) {
  const h = response.headers;
  const list = (value) =>
    (value ?? "").split(",").map((item) => item.trim().toLowerCase());

  if (response.status < 200 || response.status > 299) {
    return "blocked: preflight returned " + response.status;
  }
  const allowOrigin = h["access-control-allow-origin"];
  if (!allowOrigin) return "blocked: no Access-Control-Allow-Origin";
  if (request.credentials) {
    if (allowOrigin === "*") return "blocked: wildcard origin with credentials";
    if (h["access-control-allow-credentials"] !== "true") {
      return "blocked: credentials not allowed";
    }
  }
  if (allowOrigin !== "*" && allowOrigin !== origin) {
    return "blocked: origin " + origin + " not allowed";
  }
  if (!list(h["access-control-allow-methods"]).includes(request.method.toLowerCase())) {
    return "blocked: method " + request.method + " not allowed";
  }
  const allowedHeaders = list(h["access-control-allow-headers"]);
  const missing = request.headers.find(
    (name) => !allowedHeaders.includes(name.toLowerCase()),
  );
  if (missing) return "blocked: header " + missing + " not allowed";
  return "allowed";
}

const page = "https://app.example.com";
const headers = ["Authorization", "Content-Type"];
const put = { method: "PUT", headers, credentials: false };
const good = {
  "access-control-allow-origin": page,
  "access-control-allow-methods": "GET, PUT",
  "access-control-allow-headers": "Authorization, Content-Type",
};
const withChange = (change) => ({ status: 204, headers: { ...good, ...change } });

const other = withChange({ "access-control-allow-origin": "https://other.example" });
const noPut = withChange({ "access-control-allow-methods": "GET, POST" });
const noAuth = withChange({ "access-control-allow-headers": "Content-Type" });
const star = withChange({
  "access-control-allow-origin": "*",
  "access-control-allow-credentials": "true",
});

const scenarios = [
  ["full allowlist", put, withChange({})],
  ["auth blocks OPTIONS", put, { status: 401, headers: {} }],
  ["wrong origin", put, other],
  ["no PUT", put, noPut],
  ["Authorization missing", put, noAuth],
  ["* with cookies", { ...put, credentials: true }, star],
];
for (const [label, request, response] of scenarios) {
  console.log(label.padEnd(22) + preflightVerdict(page, request, response));
}

Quick quiz 1 / 3

A page at https://app.example.com calls fetch("https://api.example.com/items", { headers: { Authorization: "Bearer x" } }), and the API sends no CORS headers at all. What does the browser do?

Quick quiz 2 / 3

An API must accept cookie-bearing requests from https://app.example.com only. Which response headers are valid?

Quick quiz 3 / 3

Calling the API with curl works, but the browser reports a CORS error. What does that most likely mean?

What to remember

  • An origin is scheme + host + port; the browser, not the server, enforces CORS, and it only blocks reading the response while the server has already run the request.
  • GET/HEAD/POST with safelisted headers is simple; Authorization, Content-Type: application/json and PUT/DELETE need a preflight (OPTIONS).
  • Echo Allow-Origin only after an allowlist check, add Vary: Origin, never use * with credentials, and never reflect an unchecked Origin.
  • CORS is not authentication, and HTTPS secures only the transport, so token checks are still required.

RFC 9110 — HTTP Semantics — IETF

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

CORS & HTTPS | Thuta Learning