PREP WITH PROOF
Menu
PROGRAMMING & NETWORKING / PRACTICAL GUIDE

Fix CORS Errors: Preflight, Credentials and Response Headers

Diagnose failed OPTIONS requests, missing actual-response headers and credential problems. Includes curl checks and a tested origin-allowlist policy example.

THE QUICK ANSWER

Inspect the browser Network panel to identify whether preflight failed, the actual response failed CORS, or cookies were not eligible to be sent. Configure the API or gateway response for the exact allowed origin, method and request headers. Credentialed access needs an explicit origin and Access-Control-Allow-Credentials: true; curl success alone does not prove browser access.

Find the exchange that actually failed

A frontend reports “Failed to fetch,” while the same endpoint works in curl. That observation does not yet identify a CORS configuration error. A browser request can fail because of DNS, TLS, connectivity, a blocked redirect, preflight policy or the actual response. Start with the exact browser console message and the Network entries for that request.

Record the page origin, target URL, method, request headers and credentials mode. An origin includes scheme, hostname and port. https://app.example.test and https://api.example.test are different origins; so are two localhost ports. A path is not part of an origin. Compare the browser’s actual Origin header with the server allowlist rather than guessing from a deployment name.

Use the table to decide what to inspect next. Preserve status codes and a request ID, but remove tokens and personal payloads before sharing evidence. This guide’s policy function and curl-shaped HTTP exchanges were tested with a local fixture. No real browser cookie flow or production API fix is claimed.

Use one failing request as the unit of investigation. A page may call several APIs, and fixing headers on a health endpoint says nothing about the route returning the error. In Network, preserve the request chain long enough to see whether a gateway generated the response. Compare its response headers with the upstream application only after identifying which component answered.

Observed evidenceLikely boundaryNext check
OPTIONS fails; actual request absentPreflight or an earlier transport failureOPTIONS status, allow-methods and allow-headers
Actual request appears; response is blockedActual-response sharing policyAllow-origin and credential headers on that response
Response is readable; session missingCookie or authentication policyCredentials mode and cookie eligibility
Body readable; custom header returns nullResponse-header exposureExpose-headers on actual response
Works in curl onlyDifferent client enforcement/contextReproduce from the real page origin

A successful OPTIONS response needs the right agreement

A request that is not CORS-safelisted may require an OPTIONS preflight before the browser sends the application request. Common triggers include an application/json request content type, a custom request header, or a method such as PUT. POST alone does not prove a preflight is required; the complete request determines it.

The browser’s Access-Control-Request-Method names the intended method. Access-Control-Request-Headers names the request headers for which it seeks approval. The API or edge response must permit the intended exchange and return a successful status such as 204. A generic OPTIONS 200 without the necessary CORS headers is not sufficient.

A normal cross-origin preflight carries no cookies. If authentication middleware redirects OPTIONS to a login page or demands the application’s session cookie, fix that routing boundary. Let the preflight policy be evaluated without treating it as an authenticated business operation, while retaining authentication and authorization on the actual request.

The command below inspects a hypothetical read-only report query using POST and a trace header. Replace the reserved example host with an endpoint you control. These explicit headers reproduce the preflight question; curl is not deciding which requests a browser would preflight, and it will not enforce the browser’s answer.

Compare header names as well as methods when a request begins failing after a frontend release. Adding a tracing header or changing a form body to JSON can introduce a preflight into a previously working call. The API route may be unchanged while the browser’s required negotiation changes. Reproduce the new request shape instead of testing yesterday’s minimal GET.

curl -i --request OPTIONS 'https://api.example.test/reports/query' \
  --header 'Origin: https://app.example.test' \
  --header 'Access-Control-Request-Method: POST' \
  --header 'Access-Control-Request-Headers: content-type,x-trace-id'

# Inspect status and headers; do not automatically follow redirects.
# Expected policy for this approved example origin:
# Access-Control-Allow-Origin: https://app.example.test
# Access-Control-Allow-Methods: GET, POST
# Access-Control-Allow-Headers: content-type, x-trace-id

Source: WHATWG Fetch: CORS protocol ↗

Check the actual response, including error paths

Passing preflight does not exempt the actual response from its own CORS checks. A common partial fix adds headers to OPTIONS but leaves a JSON error response without Access-Control-Allow-Origin. The browser then hides the error response, leaving the frontend unable to inspect the useful API status or message.

Compare a successful response with a controlled 401, 403 or validation error from an allowed origin. The CORS policy can permit the frontend to read an error without making the operation successful. Coordinate the application, reverse proxy and CDN so one layer owns the sharing policy and error responses retain the intended headers.

Inspect for duplicate Access-Control-Allow-Origin fields or a comma-separated list of origins. That response field does not express an origin allowlist. Select one approved origin matching the request, or use an appropriate wildcard policy for genuinely public, noncredentialed access. Reflecting every arbitrary Origin while allowing credentials defeats the intended restriction.

Test the actual query separately. The illustrative command below sends synthetic data only and includes no credential. It checks response shape and headers, not a cookie-backed login. Do not substitute a real session secret into a command that will be saved in shell history or shared in a support ticket.

When several frontend environments are approved, store each complete origin as a separate allowlist entry. Do not accept a request merely because its hostname contains a familiar string. A development port should be an explicit development permission, not a reason to reflect arbitrary origins in production. Review removal of retired preview origins alongside the application’s normal access configuration.

curl -i 'https://api.example.test/reports/query' \
  --header 'Origin: https://app.example.test' \
  --header 'Content-Type: application/json' \
  --header 'X-Trace-Id: cors-learning-example' \
  --data '{"limit":3}'

# For credentialed browser use, actual responses also need:
# Access-Control-Allow-Origin: https://app.example.test
# Access-Control-Allow-Credentials: true

Source: MDN: CORS guide ↗

Separate permission to share from permission to send cookies

A cookie-backed cross-origin fetch normally needs credentials: "include" when the application intends to send eligible cookies. The response must use an explicit allowed origin together with Access-Control-Allow-Credentials: true. An allow-origin wildcard does not satisfy a request in include credentials mode, even if there happens to be no cookie available.

The credentials response value is the case-sensitive string true. Setting it to false is not the way to disable credential sharing; omit the field when that permission is not intended. Also verify the preflight response for a credentialed exchange instead of adding the field only to the final JSON response.

Even correct CORS headers cannot make an ineligible cookie appear. Inspect its domain, path, Secure, expiry and SameSite attributes, plus browser third-party-cookie restrictions. Cross-origin is not identical to cross-site: sibling HTTPS subdomains can be different origins while belonging to the same site. Do not prescribe SameSite=None for every cross-origin request.

When the intended design really requires cross-site cookies, review the cookie rules and deployment context, including the Secure requirement for SameSite=None. A missing session may be an authentication or cookie-policy problem after CORS succeeds. Keep that diagnosis separate from response sharing so a header change does not conceal the actual failure.

Source: MDN: Access-Control-Allow-Credentials ↗

Test a narrow allowlist policy before wiring middleware

This Python function models one deliberately small policy: one approved frontend origin, GET/POST application methods, and two allowed request headers. It returns a status and headers for inspection. It is not an HTTP server, authentication layer or complete middleware package. Integrating it still requires correct route handling, body validation and application error responses.

Every result varies on Origin, including denial, because the selected sharing headers depend on it. The allowed preflight method/header lists are fixed, so this example does not vary them dynamically. If your gateway varies responses by additional request fields, review the corresponding cache keys and Vary behavior. Merge existing Vary values rather than overwriting unrelated ones.

The test fixture exercised allowed and denied origins, case-insensitive request-header names, unsupported methods, unsupported headers and actual-response exposure. It also used curl against a loopback-only HTTP wrapper to inspect OPTIONS and POST response headers. That confirms HTTP output from the fixture; it does not simulate browser enforcement.

ALLOWED_ORIGINS = {"https://app.example.test"}
ALLOWED_METHODS = {"GET", "POST"}
ALLOWED_HEADERS = {"content-type", "x-trace-id"}


def cors_policy(origin, method, requested_method=None,
                requested_headers=""):
    headers = {"Vary": "Origin"}
    if origin not in ALLOWED_ORIGINS:
        return 403, headers
    if method == "OPTIONS":
        names = {x.strip().lower() for x in requested_headers.split(",")
                 if x.strip()}
        if (requested_method not in ALLOWED_METHODS
                or not names <= ALLOWED_HEADERS):
            return 403, headers
    elif method not in ALLOWED_METHODS:
        return 403, headers
    headers.update({
        "Access-Control-Allow-Origin": origin,
        "Access-Control-Allow-Credentials": "true",
    })
    if method == "OPTIONS":
        headers["Access-Control-Allow-Methods"] = "GET, POST"
        headers["Access-Control-Allow-Headers"] = "content-type, x-trace-id"
        return 204, headers
    headers["Access-Control-Expose-Headers"] = "X-Request-Id"
    return 200, headers


assert cors_policy("https://app.example.test", "OPTIONS", "POST",
                   "Content-Type, X-Trace-Id")[0] == 204
assert cors_policy("https://untrusted.example", "POST")[0] == 403

Source: MDN: Vary ↗

A visible response can still hide a custom header

If JavaScript can read the JSON body but response.headers.get("X-Request-Id") is null, inspect Access-Control-Expose-Headers on the actual response. Request-header permission and response-header exposure are different directions: allow-headers approves what the client sends, while expose-headers identifies additional response headers JavaScript may read.

For a credentialed response, list the required names explicitly. The wildcard exposure value is not a universal expose-everything shortcut with credentials; it is treated as a literal header name in that case. A request ID is a useful candidate for controlled exposure, but do not expose internal infrastructure details without a reason.

Source: MDN: Access-Control-Expose-Headers ↗

Avoid fixes that change the problem instead of solving it

Adding Access-Control-Allow-Origin to the frontend request cannot grant permission to read the server response. Those are response-policy fields. Likewise, mode: "no-cors" does not unlock a JSON API: it restricts the request and normally yields an opaque response whose body and useful status are unavailable to application code.

CORS is not authentication and does not protect an API from command-line clients. Some cross-origin requests can be sent without preflight even when the browser will not expose their responses. Retain server authorization and the appropriate CSRF protections for cookie-authenticated state changes. A browser’s inability to read a response does not prove that no server action occurred.

After changing policy, account for the browser’s separate preflight cache and any CDN caching of responses. Check the gateway actually serving the browser, not just an origin server reached by a different route. Use a fresh controlled browser test and inspect the current response rather than assuming an old console error describes the latest configuration.

The final check is an end-to-end browser request from the real approved page origin: preflight succeeds if needed, the actual response is readable, the intended cookies are eligible, and custom response headers are exposed. Repeat an error path and a disallowed-origin case. Fix the narrow failed boundary, then keep that behavior as a regression test.

Source: MDN: Request mode ↗

KEEP THESE THREE THINGS

Your next steps

  1. Identify the failed exchange before editing headers: OPTIONS, actual response, or cookie eligibility.
  2. Apply a reviewed origin allowlist and consistent response headers at one owner layer; retain authentication and CSRF controls.
  3. Retest from the real browser origin, including an error response; curl and policy unit tests verify narrower behavior.

Sources & official resources

Linked resources checked on 2026-10-24. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →