How do you fix "Request header field Access-Control-Allow-Headers is not allowed by itself in preflight"? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you fix "Request header field Access-Control-Allow-Headers is not allowed by itself in preflight"?

message-square
0

To fix Request header field Access-Control-Allow-Headers is not allowed by itself in preflight (or Access-Control-Allow-Headers cannot be used as a request header in a CORS preflight), check your client-side request headers and server/proxy CORS configuration—this error happens when client code (or a wrapper/interceptor) accidentally sends Access-Control-Allow-Headers (a response header) as a request header (Access-Control-Request-Headers lists requested headers automatically during a CORS preflight OPTIONS check), or when a reverse proxy/middleware mirrors/misconfigures request headers and triggers a CORS/preflight rejection. Remove Access-Control-Allow-Headers from outgoing request headers on the client, and on the server/API return proper CORS response headers (Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers listing allowed request headers such as Content-Type or Authorization).


1. Removing Access-Control-Allow-Headers from Client Outgoing Requests

Client requests (fetch, $.ajax, Axios, or custom request builders) should never set Access-Control-Allow-Headers on outgoing requests—only send actual request headers (like Content-Type or Authorization), and validate header keys/values before dispatching:

// Build validated request headers without accidentally sending CORS response headers
function buildSafeRequestHeaders(customHeadersMap = new Map()) {
  if (!(customHeadersMap instanceof Map)) {
    throw new TypeError("Expected customHeadersMap to be a Map of headerName -> headerValue.");
  }

  const forbiddenRequestHeaders = new Set([
    "access-control-allow-headers",
    "access-control-allow-methods",
    "access-control-allow-origin",
    "access-control-allow-credentials",
    "access-control-max-age"
  ]);

  const headersObj = {};

  try {
    for (const [rawKey, rawValue] of customHeadersMap.entries()) {
      if (typeof rawKey !== "string" || rawKey.trim().length === 0) {
        throw new TypeError("Header name must be a non-empty string.");
      }
      if (typeof rawValue !== "string") {
        throw new TypeError(`Header value for "${rawKey}" must be a string.`);
      }

      const normalizedKey = rawKey.trim().toLowerCase();
      if (forbiddenRequestHeaders.has(normalizedKey)) {
        throw new Error(`CORS response header "${rawKey.trim()}" must not be sent as a request header.`);
      }

      headersObj[rawKey.trim()] = rawValue.trim();
    }

    return headersObj;
  } catch (error) {
    throw new Error(`Failed building safe request headers: ${error.message}`); } }  // Example usage: // try { //   const headers = buildSafeRequestHeaders(new Map([ //     ["Content-Type", "application/json"], //     ["X-Requested-With", "XMLHttpRequest"] //   ])); //   console.log("Safe headers:", headers); // } catch (error) { //   console.error(`${error.name}: ${error.message}`); // }  - **Audit global AJAX/fetch wrappers and interceptors:** Check `$.ajaxSetup({ headers: ... })`, Axios defaults, or request hooks for stray `Access-Control-Allow-*` entries.
  • Keep custom headers minimal: Adding custom headers like X-Custom-Token triggers a browser OPTIONS preflight request, so only send headers the API actually expects.

2. Configuring Access-Control-Allow-Headers Properly on a Node.js Server

On the server / API, handle OPTIONS preflight requests and respond with Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers (listing the headers requested in Access-Control-Request-Headers or an explicit allow-list):

// Node.js http CORS preflight and response helper with explicit header allow-listing
function applyCorsHeaders(req, res, allowedOriginsSet, allowedHeadersList = ["Content-Type", "Authorization"]) {
  if (!req || !res || typeof res.setHeader !== "function") {
    throw new TypeError("Expected valid Node.js req and res objects.");
  }
  if (!(allowedOriginsSet instanceof Set)) {
    throw new TypeError("Expected allowedOriginsSet to be a Set of allowed origin strings.");
  }
  if (!Array.isArray(allowedHeadersList)) {
    throw new TypeError("Expected allowedHeadersList to be an array of header names.");
  }

  try {
    const origin = typeof req.headers?.origin === "string" ? req.headers.origin : "";
    if (origin && allowedOriginsSet.has(origin)) {
      res.setHeader("Access-Control-Allow-Origin", origin);
      res.setHeader("Vary", "Origin");
    }

    res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");

    const sanitizedAllowedHeaders = allowedHeadersList
      .filter((h) => typeof h === "string" && h.trim().length > 0)
      .map((h) => h.trim());

    res.setHeader("Access-Control-Allow-Headers", sanitizedAllowedHeaders.join(", "));
    res.setHeader("Access-Control-Max-Age", "86400");

    if (req.method === "OPTIONS") {
      res.statusCode = 204;
      res.end();
      return true;
    }

    return false;
  } catch (error) {
    throw new Error(`Failed applying CORS headers: ${error.message}`);
  }
}

// Example usage inside a Node http server:
// const origins = new Set(["https://app.example.com"]);
// if (applyCorsHeaders(req, res, origins, ["Content-Type", "Authorization"])) return;
  • Return 204 No Content (or 200 OK) for OPTIONS preflight requests: Ensure middleware or auth guards do not block OPTIONS before CORS headers are sent.
  • Avoid wildcard * for Access-Control-Allow-Origin when credentials (withCredentials / credentials: "include") are used: Echo the validated request Origin explicitly and set Access-Control-Allow-Credentials: true only when needed.

3. Reverse Proxies, CDNs, and Browser Cache Caveats

When behind Nginx, Apache, Cloudflare, or an API Gateway, check proxy rules and cached preflight responses:

  • Prevent duplicate or conflicting CORS headers at the proxy layer: If both an upstream Node.js app and Nginx/API Gateway set Access-Control-Allow-Headers, browsers can reject combined/conflicting headers.
  • Clear stale preflight cache during debugging: Browsers cache OPTIONS preflight results for Access-Control-Max-Age seconds; test with DevTools Network tab (Disable cache) or temporarily lower Access-Control-Max-Age while fixing headers.
  • Check exact header spelling (case-insensitive per HTTP spec, but watch for typos): Ensure client request headers match the server’s Access-Control-Allow-Headers list.