What causes "TypeError: Failed to fetch" in JavaScript Fetch API even when the server responds? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

What causes "TypeError: Failed to fetch" in JavaScript Fetch API even when the server responds?

message-square
0

In the JavaScript Fetch API, TypeError: Failed to fetch occurs even when the server responds whenever the browser blocks, aborts, or rejects the network/response pipeline before or during response settlement—most commonly due to missing or invalid CORS response headers (Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, or Access-Control-Allow-Credentials on credentialed requests), mixed content / TLS / certificate failures (https page requesting an insecure http endpoint or invalid TLS cert), request abortion / timeout (AbortController.abort()), network drop / DNS failure / browser extension or proxy interference, or response body stream / Response object misuse—so validate inputs and Response instances with typeof / instanceof checks, inspect diagnostic causes in a Map, and wrap fetch execution and body consumption inside try / catch blocks.


1. Diagnosing "TypeError: Failed to fetch" Across CORS, TLS, and Abort Causes with a Map

When a server returns a status code (such as 200, 401, or 500) in network logs yet fetch() rejects with TypeError: Failed to fetch, the browser has refused to expose the response to JavaScript or aborted the transaction; inspect probable causes in a Map inside try / catch:

// Diagnose likely causes when fetch() throws "TypeError: Failed to fetch" despite server activity
function diagnoseFailedFetchCause({
  requestUrl = "",
  pageProtocol = (typeof window !== "undefined" && window.location ? window.location.protocol : "https:"),
  hasCrossOrigin = false,
  usesCredentials = false,
  wasAborted = false
} = {}) {
  if (typeof requestUrl !== "string") {
    throw new TypeError("Expected requestUrl to be a string.");
  }
  if (typeof pageProtocol !== "string" || pageProtocol.trim().length === 0) {
    throw new TypeError("Expected pageProtocol to be a non-empty string.");
  }
  if (typeof hasCrossOrigin !== "boolean") {
    throw new TypeError("Expected hasCrossOrigin to be a boolean.");
  }
  if (typeof usesCredentials !== "boolean") {
    throw new TypeError("Expected usesCredentials to be a boolean.");
  }
  if (typeof wasAborted !== "boolean") {
    throw new TypeError("Expected wasAborted to be a boolean.");
  }

  try {
    const cleanUrl = requestUrl.trim();
    const cleanPageProto = pageProtocol.trim().toLowerCase();
    const isMixedContent = cleanPageProto === "https:" && cleanUrl.toLowerCase().startsWith("http://");
    const causes = [];

    if (hasCrossOrigin) {
      causes.push("Missing or mismatched CORS headers on server response or OPTIONS preflight (e.g., Access-Control-Allow-Origin)");
    }
    if (usesCredentials && hasCrossOrigin) {
      causes.push("Credentialed cross-origin request requires Access-Control-Allow-Credentials: true and non-wildcard Access-Control-Allow-Origin");
    }
    if (isMixedContent) {
      causes.push("Mixed content block: HTTPS page attempting to fetch an HTTP endpoint");
    }
    if (wasAborted) {
      causes.push("Request aborted via AbortController signal or timeout");
    }
    if (causes.length === 0) {
      causes.push("Check TLS/SSL certificate validity, network/proxy/ad-blocker interference, or response body stream errors");
    }

    return new Map([
      ["requestUrl", cleanUrl || "(unspecified)"],
      ["isMixedContent", isMixedContent],
      ["suspectedCauses", causes],
      ["checkLayers", ["Browser Console", "DevTools Network Timing/CORS", "Server Response Headers"]]
    ]);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed diagnosing fetch failure: ${message}`);
  }
}

// Example usage:
// try {
//   const diagMap = diagnoseFailedFetchCause({
//     requestUrl: "https://api.example.com/v1/data",
//     hasCrossOrigin: true,
//     usesCredentials: true
//   });
//   console.log("Suspected causes:", diagMap.get("suspectedCauses"));
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • CORS failures often surface as TypeError: Failed to fetch in JS: Even when the server sends a response, if required CORS headers are missing or invalid, the browser blocks reading it and rejects the fetch() promise.
  • Credentialed requests (credentials: "include") have strict CORS rules: The server cannot use Access-Control-Allow-Origin: * when credentials are included; it must echo the exact origin and send Access-Control-Allow-Credentials: true.

2. Executing fetch() Safely with Explicit Validation, Map Metadata, and try / catch

Validate parameters, Response instance, and body parsing, and track request outcomes in a Map so dynamic keys never collide with Object.prototype properties:

// Perform a defensive fetch() call with explicit validation, Map result metadata, and try / catch
async function safeFetchWithDiagnostics(targetUrl, initOptions = {}) {
  if (typeof targetUrl !== "string" || targetUrl.trim().length === 0) {
    throw new TypeError("Expected targetUrl to be a non-empty string.");
  }
  if (typeof initOptions !== "object" || initOptions === null || Array.isArray(initOptions)) {
    throw new TypeError("Expected initOptions to be a non-null plain/record object.");
  }
  if (typeof fetch !== "function") {
    throw new Error("Global fetch() function is not available in this environment.");
  }

  const cleanUrl = targetUrl.trim();

  try {
    const response = await fetch(cleanUrl, initOptions);
    if (!(response instanceof Response)) {
      throw new Error("Expected fetch() to return a Response instance.");
    }

    const rawBody = await response.text();
    let parsedJson = null;

    if (rawBody.trim().length > 0) {
      try {
        parsedJson = JSON.parse(rawBody);
      } catch (parseError) {
        const parseMsg = parseError instanceof Error ? parseError.message : String(parseError);
        throw new SyntaxError(`Response body was not valid JSON: ${parseMsg}`);
      }
    }

    return new Map([
      ["url", cleanUrl],
      ["ok", response.ok],
      ["status", response.status],
      ["statusText", response.statusText],
      ["data", parsedJson]
    ]);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Fetch failed for "${cleanUrl}": ${message}`);
  }
}

// Example usage:
// try {
//   const outcomeMap = await safeFetchWithDiagnostics("https://api.example.com/v1/status", {
//     method: "GET",
//     credentials: "same-origin"
//   });
//   console.log("HTTP status:", outcomeMap.get("status"), "OK:", outcomeMap.get("ok"));
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • Use Map for response metadata: Avoids collisions with Object.prototype properties (constructor, toString, hasOwnProperty).
  • Separate network/CORS/abort rejections from HTTP 4xx/5xx statuses: fetch() only rejects with TypeError on network/protocol/CORS/abort/stream failures, whereas 4xx/5xx resolve with response.ok === false.

3. Preflight Errors, Body Consumption, and Browser Caveats

Keep these Fetch API edge cases in mind when debugging Failed to fetch:

  • Failed OPTIONS preflight requests cause Failed to fetch: If a non-safelisted method (PUT, DELETE, PATCH) or custom/JSON header triggers an OPTIONS preflight and the server does not return 200/204 with matching CORS headers, the main request never completes cleanly in JS.
  • Response body streams can only be consumed once: Calling .json() after .text() (or reading an already-locked stream) throws an error; read once and parse safely.
  • Check DevTools Console alongside Network tab: The Network tab may show a status code or (failed) while the Console pinpoints the exact CORS, mixed-content, or TLS error.