TypeError: Failed to Fetch: What It Really Means and How to Find the Cause in Production

TypeError: Failed to fetch is one of the most common errors in browser JavaScript, and one of the least helpful. It tells you that a fetch() call never got a response the page was allowed to read. It does not tell you why. The same message covers a CORS misconfiguration, a dropped mobile connection, an ad blocker, an expired certificate and a user who clicked a link before the request finished. This post explains what the error actually means, lists the causes in the order you are most likely to hit them, and shows how to collect enough context in production to tell them apart.
Prerequisites
The code in this post runs as written with:
- A current version of Chrome, Edge, Firefox or Safari.
AbortSignal.timeout()needs Chrome 103, Firefox 100 or Safari 16 and later. - Any bundler or plain ES modules. Nothing here depends on a framework.
- Optionally, the Appxiom Web SDK (
npm install @appxiom/web) if you want failed requests captured with their activity trail. Setup steps are in the Web SDK installation guide.
What "Failed to fetch" means, and what it does not
fetch() only rejects when the request fails at the network level. An HTTP 404 or 500 is a successful fetch: the promise resolves, and res.ok is false. So when you see TypeError: Failed to fetch, the server's status code is not the problem, because the browser never handed your code a response at all.
The wording depends on the browser, which matters when you search your logs:
| Browser | Message for the same failure |
|---|---|
| Chrome, Edge | TypeError: Failed to fetch |
| Firefox | TypeError: NetworkError when attempting to fetch resource. |
| Safari | TypeError: Load failed |
Group all three together in your error tracking, or a single cause will look like three small issues.
The browser also hides the reason from JavaScript on purpose. If a script could tell "blocked by CORS" apart from "host unreachable", it could probe a user's private network. The real reason only shows up in the DevTools console and the Network panel, which is why this error is easy to fix on your own machine and hard to fix from a production log.
The common causes of TypeError: Failed to fetch
Most cases fall into one of these groups. The DevTools column is what you will see locally if you can reproduce it.
| Cause | Typical trigger | What DevTools shows |
|---|---|---|
| CORS | API on another origin is missing Access-Control-Allow-Origin, or the preflight fails | A CORS error in the console, request marked as CORS error |
| Error response without CORS headers | Proxy or gateway returns 502 or 504 without the headers your app server would add | Same CORS error, although the real problem is a server failure |
| Network loss | Offline, DNS failure, VPN drop, captive portal Wi-Fi | net::ERR_INTERNET_DISCONNECTED, ERR_NAME_NOT_RESOLVED |
| Blocked by the client | Ad blocker or privacy extension matches the URL | net::ERR_BLOCKED_BY_CLIENT |
| Mixed content | HTTPS page calls an http:// URL | Mixed content warning, request blocked |
| Content Security Policy | connect-src does not include the API host | CSP violation in the console |
| Navigation or tab close | User leaves the page while the request is in flight | Request shown as cancelled |
| Connection reset | Server or load balancer closes the socket, TLS failure | ERR_CONNECTION_RESET, ERR_CERT_* |
The second row deserves attention. When your API fails behind a load balancer, the error page usually comes from the proxy, not your application, and it often has no CORS headers. The browser blocks it, and your code sees Failed to fetch instead of a 502. Teams spend days on CORS settings when the real fix is in the backend that is timing out. Configure the proxy to add CORS headers on error responses too, and the same failure shows up as a status code you can act on.
Fix the CORS case first
If the error reproduces on every request from one origin, it is almost always CORS. The response to a cross-origin request needs headers like these:
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true
Three details catch people out:
- A request with a JSON body or an
Authorizationheader triggers a preflightOPTIONSrequest. The server must answer thatOPTIONScall with a 2xx and the same headers, and many frameworks route it to a handler that returns 404 or 405. - With
credentials: 'include', the origin must be named exactly.Access-Control-Allow-Origin: *is rejected. - Setting
mode: 'no-cors'hides the error but gives you an opaque response with no body. It is almost never what you want for an API call.
Add timeouts and classify the failure in code
fetch() has no timeout of its own. A request to a slow backend can hang until the browser gives up, and what the user sees is a spinner that never stops. Add an explicit timeout with AbortSignal.timeout(), and sort the error into a type before you log it.
Here is a wrapper that does both. It throws a different, named error for each failure type, so your logs and your UI can treat them differently.
export class HttpError extends Error {
constructor(status, url) {
super(`HTTP ${status} for ${url}`);
this.name = 'HttpError';
this.status = status;
}
}
export async function request(url, options = {}, timeoutMs = 10000) {
const timeout = AbortSignal.timeout(timeoutMs);
const signal = options.signal
? AbortSignal.any([options.signal, timeout])
: timeout;
let res;
try {
res = await fetch(url, { ...options, signal });
} catch (err) {
if (err.name === 'TimeoutError') {
throw new Error(`Timed out after ${timeoutMs} ms: ${url}`, { cause: err });
}
if (err.name === 'AbortError') {
throw err; // Cancelled on purpose, usually safe to ignore.
}
// A TypeError here is the "Failed to fetch" family.
const context = {
online: navigator.onLine,
visibility: document.visibilityState,
host: new URL(url, location.href).host,
};
throw new Error(`Network failure: ${url} ${JSON.stringify(context)}`, { cause: err });
}
if (!res.ok) {
throw new HttpError(res.status, url);
}
return res;
}
A few notes on why this works:
- A timeout raised by
AbortSignal.timeout()rejects with aDOMExceptionnamedTimeoutError, not aTypeError, so slow backends stop hiding inside the "Failed to fetch" bucket. AbortSignal.any()keeps the caller's ownAbortControllerworking, for example when a React effect cancels a request on unmount. It needs Chrome 116, Firefox 124 or Safari 17.4. If you support older browsers, drop the merge and pass one signal.navigator.onLineanddocument.visibilityStateare cheap and tell you a lot. A failure withonline: falseis a connectivity problem. A failure withvisibility: hiddenis very often a user who switched tabs or left the page.
To use it, call request() where you used to call fetch(), and keep the try/catch in the caller:
try {
const res = await request('/api/cart', { method: 'GET' }, 8000);
renderCart(await res.json());
} catch (err) {
showRetryBanner();
reportError(err);
}
Stop counting navigation aborts as bugs
A large share of production "Failed to fetch" reports come from requests that were cut off because the user left. They click a link, close the tab or the mobile browser freezes the page in the background, and every request still in flight fails. Nothing is broken, but these reports bury the real failures.
Two changes clean this up:
- For analytics and "fire and forget" calls made while the page unloads, use
navigator.sendBeacon()orfetch(url, { keepalive: true }). The browser finishes them after the page is gone. - In your error reporting, tag failures where
document.visibilityStatewashiddenat the time, and review them separately.
Once these are filtered, what remains is a much smaller list, and it is usually the list that matters.
Finding the cause in production
Locally you have DevTools. In production you have a message and a stack that ends inside your bundle. To find the cause, you need what was around the failure: which request it was, which browser and version, whether the user was online, what they had just done and whether it stopped them from finishing.
Here is an illustrative case. A web shop sees a steady few hundred Failed to fetch errors a day and treats them as background noise from bad connections. Grouped by URL, nearly all of them come from one endpoint, the shipping quote call on the checkout page. Grouped by browser, they cluster on Safari after a release that added a custom header to that call. The new header triggered a preflight that the API gateway did not allow. Every one of those errors was a customer who could not see shipping costs and left the checkout.
The count never changed much. What changed the priority was knowing the request, the browser and the journey it broke.
See which failed request is breaking a journey. The Appxiom Web SDK records failed network calls as structured issues:
HTTPExceptionErrorfor requests that fail without a response,HTTPStatusErrorfor 4xx and 5xx responses andHTTPDelayedResponseErrorfor slow ones. Each occurrence comes with the activity trail, so you can see the request, the browser and the steps before it. Connect your coding agent to the Appxiom MCP server and ask: "Which failed network requests on the web app have the highest Goal Friction Impact this week?" The agent gets the issues with their occurrence telemetry, and you decide what to fix first.
To rank failures by impact, define the journeys that matter. With the Web SDK you mark them with startGoal and endGoal:
ax.startGoal('checkout-flow');
// ... cart, shipping quote, payment ...
ax.endGoal('checkout-flow', { cartValue: 120.0 }, 120.0);
Appxiom then scores issues with Goal Friction Impact, so a failed request that blocks checkout ranks above one that only affects a recommendations widget. Our post on Goal Friction Impact and the revenue cost of broken user journeys explains how the score works, and session replay vs activity trail covers why a timestamped trail is often quicker to debug from than a recording.
Failed to fetch and unhandled promise rejections
When fetch() rejects and nothing catches it, the same error also shows up as Uncaught (in promise) TypeError: Failed to fetch. That is two problems at once: a network failure, and a promise with no handler. The wrapper above fixes the first. For the second, see our guide to unhandled promise rejections in JavaScript, which covers the patterns that leave promises without a .catch() and the global unhandledrejection listener that catches what slips through.
Mobile teams face the same split between network failures and HTTP errors on Android and iOS. If you ship both, how to detect HTTP(S) call issues in mobile apps covers that side.
A checklist for TypeError: Failed to fetch
- Search for all three browser messages together:
Failed to fetch,NetworkError when attempting to fetch resourceandLoad failed. - Reproduce with DevTools open and read the console line next to the error. It names the real cause.
- If it is CORS, check the preflight
OPTIONSresponse, not only the main request. - Make sure proxies and gateways add CORS headers to their error responses.
- Give every request an explicit timeout with
AbortSignal.timeout(). - Check
res.okon every response, because 4xx and 5xx never throw. - Log
navigator.onLine,document.visibilityState, the request host and the browser with every network failure. - Use
keepaliveorsendBeaconfor requests made while the page unloads.
Treat the message as a starting point
TypeError: Failed to fetch is a category, not a diagnosis. Most of the reports in a typical production log are harmless aborts and flaky connections, and a few are a CORS rule, a gateway or a release that quietly stopped users from finishing a task. The work is telling those apart, which takes the request, the browser and the journey for each failure. Coding agents can help with the fix once they have that production context, as we wrote in your AI coding agent can write the fix, but it can't see production.
To start capturing failed requests from your own web app with that context, follow the Appxiom Web SDK quickstart. It takes one npm install and a single init call.


