Why does jQuery AJAX trigger an Access-Control-Request-Headers CORS preflight request? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

Why does jQuery AJAX trigger an Access-Control-Request-Headers CORS preflight request?

message-square
0

jQuery AJAX ($.ajax()) triggers a CORS OPTIONS preflight request including Access-Control-Request-Headers whenever a cross-origin request is not a CORS “safelisted” request—most commonly in jQuery because contentType defaults to "application/x-www-form-urlencoded; charset=UTF-8" or is explicitly set to a non-safelisted type such as "application/json", or because custom/non-safelisted request headers (such as Authorization or custom X-* headers) are sent—so validate inputs with typeof / instanceof checks, inspect/manage headers and preflight diagnostics in a Map, and wrap logic in try / catch blocks.


1. Inspecting and Building $.ajax() Headers That Trigger Access-Control-Request-Headers

Safelisted Content-Type values for simple CORS requests are only application/x-www-form-urlencoded, multipart/form-data, and text/plain (without special parameters/headers); setting contentType: "application/json" or sending custom headers causes the browser to send an OPTIONS preflight with Access-Control-Request-Headers:

// Classify whether a jQuery $.ajax() configuration will trigger a CORS preflight
function evaluateAjaxCorsPreflight(ajaxConfig, {
  jqueryRef = (typeof $ !== "undefined" ? $ : null)
} = {}) {
  if (typeof jqueryRef !== "function") {
    throw new TypeError("Expected jqueryRef to be a valid jQuery ($) function.");
  }
  if (typeof ajaxConfig !== "object" || ajaxConfig === null || Array.isArray(ajaxConfig)) {
    throw new TypeError("Expected ajaxConfig to be a non-null plain/record object.");
  }

  try {
    const safelistedMethods = new Set(["GET", "HEAD", "POST"]);
    const safelistedMimeTypes = new Set([
      "application/x-www-form-urlencoded",
      "multipart/form-data",
      "text/plain"
    ]);

    const method = typeof ajaxConfig.type === "string"
      ? ajaxConfig.type.trim().toUpperCase()
      : (typeof ajaxConfig.method === "string" ? ajaxConfig.method.trim().toUpperCase() : "GET");

    const rawContentType = typeof ajaxConfig.contentType === "string"
      ? ajaxConfig.contentType.trim().toLowerCase()
      : "application/x-www-form-urlencoded";

    const baseMimeType = rawContentType.split(";")[0].trim();
    const extraHeadersMap = new Map();

    if (typeof ajaxConfig.headers === "object" && ajaxConfig.headers !== null && !Array.isArray(ajaxConfig.headers)) {
      for (const [headerName, headerVal] of Object.entries(ajaxConfig.headers)) {
        if (typeof headerName === "string" && headerName.trim().length > 0 && typeof headerVal === "string") {
          extraHeadersMap.set(headerName.trim().toLowerCase(), headerVal);
        }
      }
    }

    const requestedHeaders = [];
    let requiresPreflight = false;

    if (!safelistedMethods.has(method)) {
      requiresPreflight = true;
    }

    if (baseMimeType.length > 0 && !safelistedMimeTypes.has(baseMimeType)) {
      requiresPreflight = true;
      requestedHeaders.push("content-type");
    }

    for (const [headerKey] of extraHeadersMap.entries()) {
      // Accept, Accept-Language, Content-Language, and Content-Type (safelisted) do not trigger preflight alone
      const isSafelistedHeader =
        headerKey === "accept" ||
        headerKey === "accept-language" ||
        headerKey === "content-language" ||
        (headerKey === "content-type" && safelistedMimeTypes.has(baseMimeType));

      if (!isSafelistedHeader) {
        requiresPreflight = true;
        requestedHeaders.push(headerKey);
      }
    }

    return new Map([
      ["method", method],
      ["baseContentType", baseMimeType],
      ["requiresPreflight", requiresPreflight],
      ["accessControlRequestHeaders", requestedHeaders]
    ]);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed evaluating $.ajax() CORS preflight rules: ${message}`);
  }
}

// Example usage:
// try {
//   const preflightInfo = evaluateAjaxCorsPreflight({
//     url: "https://api.example.com/v1/orders",
//     type: "POST",
//     contentType: "application/json",
//     headers: { Authorization: "Bearer <token>", "X-Request-Id": "req-42" }
//   });
//   console.log("Needs preflight:", preflightInfo.get("requiresPreflight"));
//   console.log("Requested headers:", preflightInfo.get("accessControlRequestHeaders"));
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • Preflight is a browser security behavior, not a jQuery bug: jQuery passes options to XMLHttpRequest (xhr.setRequestHeader(...)), and the browser automatically sends OPTIONS with Access-Control-Request-Headers.
  • Both contentType and headers / beforeSend can add headers: Any header beyond safelisted ones is listed in Access-Control-Request-Headers during the preflight check.

2. Executing a Validated $.ajax() Call with Header Tracking in a Map

When running cross-origin $.ajax() calls in production, validate jQuery and parameters up front, track request headers in a Map, and handle errors inside try / catch:

// Run a validated $.ajax() request while tracking custom/non-safelisted headers in a Map
function executeValidatedAjaxRequest(requestConfig, {
  jqueryRef = (typeof $ !== "undefined" ? $ : null)
} = {}) {
  if (typeof jqueryRef !== "function") {
    throw new TypeError("Expected jqueryRef to be a valid jQuery ($) function.");
  }
  if (typeof requestConfig !== "object" || requestConfig === null || Array.isArray(requestConfig)) {
    throw new TypeError("Expected requestConfig to be a non-null plain/record object.");
  }
  if (typeof requestConfig.url !== "string" || requestConfig.url.trim().length === 0) {
    throw new TypeError("Expected requestConfig.url to be a non-empty string.");
  }

  try {
    const headerRegistryMap = new Map();
    const method = typeof requestConfig.type === "string"
      ? requestConfig.type.trim().toUpperCase()
      : (typeof requestConfig.method === "string" ? requestConfig.method.trim().toUpperCase() : "GET");

    if (typeof requestConfig.contentType === "string" && requestConfig.contentType.trim().length > 0) {
      headerRegistryMap.set("Content-Type", requestConfig.contentType.trim());
    }

    if (typeof requestConfig.headers === "object" && requestConfig.headers !== null && !Array.isArray(requestConfig.headers)) {
      for (const [k, v] of Object.entries(requestConfig.headers)) {
        if (typeof k === "string" && k.trim().length > 0 && typeof v === "string") {
          headerRegistryMap.set(k.trim(), v);
        }
      }
    }

    const plainHeaders = {};
    for (const [headerName, headerValue] of headerRegistryMap.entries()) {
      plainHeaders[headerName] = headerValue;
    }

    const ajaxOptions = {
      url: requestConfig.url.trim(),
      method,
      headers: plainHeaders,
      data: requestConfig.data
    };

    if (typeof requestConfig.contentType === "string") {
      ajaxOptions.contentType = requestConfig.contentType;
    }

    return jqueryRef.ajax(ajaxOptions);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed starting jQuery $.ajax() request: ${message}`);
  }
}

// Example usage:
// try {
//   const jqXhr = executeValidatedAjaxRequest({
//     url: "https://api.example.com/v1/profile",
//     method: "GET",
//     headers: { Authorization: "Bearer <token>" }
//   });
//   jqXhr.done((payload) => console.log("Success:", payload));
//   jqXhr.fail((xhr, status, err) => console.error("AJAX failed:", status, err));
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • Use Map for header entries before building the plain header object: Avoids Object.prototype key collisions on dynamic header names.
  • Server must allow requested headers in Access-Control-Allow-Headers: If the server omits a header listed in Access-Control-Request-Headers (or does not respond 200/204 to OPTIONS), the browser blocks the actual request.

3. Server CORS Response Headers, $.ajaxSetup(), and Preflight Caveats

Keep these CORS and jQuery details in mind when debugging preflight requests:

  • Server must return Access-Control-Allow-Origin and Access-Control-Allow-Headers on the OPTIONS preflight: Wildcard * in Access-Control-Allow-Headers is not universally treated identically to explicit header names across all browsers/proxies—explicitly listing allowed headers (such as Content-Type, Authorization) is safest.
  • Watch global $.ajaxSetup() or beforeSend hooks: Global hooks can inject custom headers onto calls you thought were simple requests, triggering an unexpected preflight.
  • Same-origin requests do not trigger CORS preflight: A preflight only happens when protocol, domain (host), or port differs between the page origin and target URL.