How does the Access-Control-Allow-Origin HTTP response header control CORS? | A1Lab@FahadM to JavaScriptEnglish • 6 days ago

How does the Access-Control-Allow-Origin HTTP response header control CORS?

message-square
0

The Access-Control-Allow-Origin HTTP response header tells the browser which request origin(s) are allowed to read the response of a cross-origin request initiated by client-side JavaScript (such as fetch() or XMLHttpRequest). Cross-Origin Resource Sharing (CORS) is enforced by the browser—not by the server—and Access-Control-Allow-Origin acts as the server’s explicit opt-in permission slip for cross-origin response access.


1. How the Browser Checks Access-Control-Allow-Origin

When a page on https://app.example.com makes a cross-origin request to https://api.example.org:

  • Request origin sent: The browser attaches an Origin: https://app.example.com header to cross-origin requests.

  • Response header evaluated: The server responds with Access-Control-Allow-Origin set to either the exact requesting origin (https://app.example.com), a wildcard (*), or omitted/mismatched.

  • Read access granted or blocked: If the header matches the requesting origin (or is * when credentials are not used), JavaScript can read the response body/headers. If not, the browser blocks JavaScript from reading the response and logs a CORS error—even if the server returned 200 OK and actually processed the request.

    // Express / Node.js example: allowing a specific trusted origin app.use((req, res, next) => { const allowedOrigins = new Set([“https://app.example.com”, “http://localhost:5173”]); const requestOrigin = req.headers.origin;

    if (requestOrigin && allowedOrigins.has(requestOrigin)) {
      res.setHeader("Access-Control-Allow-Origin", requestOrigin);
      res.setHeader("Vary", "Origin");
    }
    
    next();
    

    });

2. Wildcard (*) vs. Specific Origin and Credentials

Choosing between * and a specific origin depends on whether your endpoints are public and whether cookies or credentialed requests are involved:

  • Wildcard (Access-Control-Allow-Origin: *): Allows any origin to read the response—great for public, unauthenticated APIs or static assets. It cannot be used when the request includes credentials (credentials: "include" in fetch()), such as cookies or Authorization headers that rely on credentialed CORS rules.

  • Dynamic specific origin + Vary: Origin: When your API serves multiple approved origins, echo back the validated Origin header rather than joining multiple origins into one comma-separated string (standard Access-Control-Allow-Origin accepts a single origin or *), and include Vary: Origin so caches do not serve one origin’s header to another.

  • Preflight (OPTIONS) requests: For non-simple requests (such as custom headers or application/json with certain methods/headers), the browser sends an OPTIONS preflight first and checks Access-Control-Allow-Origin on the preflight response before sending the actual request.

    // When using credentials (e.g. cookies) with a specific origin res.setHeader(“Access-Control-Allow-Origin”, “https://app.example.com”); res.setHeader(“Access-Control-Allow-Credentials”, “true”); res.setHeader(“Vary”, “Origin”);

3. Common Traps to Avoid

  • Thinking CORS stops the server from receiving requests: A missing Access-Control-Allow-Origin header does not prevent a POST or DELETE from hitting your server; it prevents the browser from exposing the response to frontend JS.
  • Putting multiple comma-separated origins in Access-Control-Allow-Origin: Returning Access-Control-Allow-Origin: https://a.com, https://b.com is invalid per the CORS spec and fails browser checks—echo one validated origin per response instead.
  • Forgetting Vary: Origin when echoing origins dynamically: Without Vary: Origin, intermediate proxies or CDNs can cache the response for one origin and break or expose it for another.

TL;DR: Access-Control-Allow-Origin tells the browser which origin may expose a cross-origin response to JavaScript—use * for public non-credentialed endpoints, or echo a single validated origin with Vary: Origin (and Access-Control-Allow-Credentials: true when credentials are required).

Are you configuring CORS for a public API, handling cookie/credentialed requests across subdomains, or debugging a preflight (OPTIONS) issue?