Quick answer: fetch rejects with this TypeError only when no response arrives at all; a 404 or 500 resolves normally. Chrome says Failed to fetch, Firefox NetworkError when attempting to fetch resource. and Safari Load failed. JavaScript is never told why, but the DevTools console and Network tab are: CORS, mixed content, a blocker, a Content-Security-Policy or the network itself. Fix that cause, then add a timeout, retries for idempotent requests and a visible offline state.
The leaderboard works on your machine and on your own domain. Then the game goes onto a portal, or a player with an ad blocker opens it, or someone plays on a train, and the error reports fill with one identical line that names no URL and no reason. The message is deliberately empty: browsers do not reveal to scripts why a request to another origin failed. This guide covers what the error does and does not mean, where the real reason is written down, a table from reason to fix, why portals break calls that worked elsewhere, and a small safeFetch helper that keeps a failed request from taking the game down with it.
- The exact error
- What it means
- Where the real reason is written
- Reason, cause and fix
- Why it works on your domain and fails on a portal
- Requests that die when the page closes
- A safeFetch helper
- Keep the game running when a request fails
- Report it so it can be acted on
- How to confirm the fix
- What a network failure looks like in Bugnet
- Related guides
- Frequently asked questions
The exact error
Uncaught (in promise) TypeError: Failed to fetch (Chrome, Edge)
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource. (Firefox)
Unhandled Promise Rejection: TypeError: Load failed (Safari)
The three strings are one condition. Do not match on the text in code: test for a TypeError from fetch, or better, wrap fetch once and classify failures there, as the helper further down does.
What it means
fetch rejects only when the request produced no response. An HTTP error status is a response: a 404, a 500 or a 403 from your API resolves the promise normally with response.ok set to false. So this error never means “the server said no”. It means the request was blocked before it left, was refused by the browser when the answer came back, or died on the network.
const response = await fetch("/api/scores"); // rejects: no response at all
if (!response.ok) { // resolves: the server answered with an error
throw new Error("Scores request failed with HTTP " + response.status);
}
const scores = await response.json(); // rejects if the connection drops mid-body
A connection that drops while the body is still downloading rejects the body read instead, so keep response.json() inside the same try block as the fetch. An aborted request rejects with a different error, a DOMException named AbortError (or TimeoutError when you used AbortSignal.timeout()).
Where the real reason is written
The page cannot read the reason, but DevTools can show it. Reproduce the failure with the console open.
- Chrome and Edge. The console prints a second line next to the TypeError: a CORS explanation, a mixed content or Content-Security-Policy message, or
Failed to load resource: net::ERR_.... In the Network tab the Status column showsCORS error,(blocked:...),(canceled)or(failed)with the samenet::ERR_code. - Firefox. CORS failures appear as
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ...followed by a reason in brackets. The Network panel names the extension when one blocked the request. - Safari. Look for
Fetch API cannot load ... due to access control checks.for CORS, or a message about the connection.
If the failure only happens for players, you will not have their console. That is what the reporting section is for.
Reason, cause and fix
| What Chrome shows | Cause | Fix |
|---|---|---|
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present | The API does not allow the origin the game is running on | Send Access-Control-Allow-Origin for every origin the game is served from, portals included |
Response to preflight request doesn't pass access control check | A custom header or a JSON Content-Type made the browser send an OPTIONS request first, and the server did not answer it properly | Answer OPTIONS with a 2xx status, Access-Control-Allow-Methods and Access-Control-Allow-Headers |
must not be the wildcard '*' when the request's credentials mode is 'include' | Cookies were requested but the server allows * | Echo the exact origin and add Access-Control-Allow-Credentials: true, or stop sending credentials |
A console line starting Mixed Content: | An http:// API called from an https:// page | Serve the API over HTTPS |
net::ERR_BLOCKED_BY_CLIENT | An ad blocker or privacy extension matched the URL, typically a host or path containing words like ads, analytics or track | Never let gameplay depend on these calls; use neutral paths on your own host for things that matter |
net::ERR_INTERNET_DISCONNECTED, net::ERR_NAME_NOT_RESOLVED, net::ERR_NETWORK_CHANGED | Offline, DNS failure, switching between Wi-Fi and mobile data, a captive portal | Retry with backoff and show an offline state |
net::ERR_CONNECTION_REFUSED | Nothing is listening: the server is down, or the build still points at localhost | Configure the API URL per environment and check it in the shipped build |
net::ERR_CONNECTION_RESET, net::ERR_EMPTY_RESPONSE, net::ERR_HTTP2_PROTOCOL_ERROR, net::ERR_CONNECTION_TIMED_OUT | The server, proxy or load balancer dropped the connection: a body over its size limit, an idle timeout, a restart during a deploy | Check proxy limits and logs; retry idempotent requests |
net::ERR_CERT_DATE_INVALID and other ERR_CERT_ codes | Expired or mismatched certificate, or a wrong clock on the player’s device | Renew and monitor the certificate |
violates the following Content Security Policy directive: "connect-src ..." | The page’s CSP, yours or the portal’s, does not list the host | Add the host to connect-src, or use what the portal allows |
(canceled), net::ERR_ABORTED | The page navigated, reloaded or closed while the request was in flight | Use keepalive or sendBeacon (below) |
Cross origin requests are only supported for protocol schemes: ... | The game was opened from file:// | Run a local web server |
Two more that depend on the browser. Chrome 142 and later ask the player for permission before a public page may call localhost or a private network address, and the request fails if that is declined, so a leftover development URL fails in a new way. And Safari’s cookie restrictions do not cause this error by themselves: the request goes out without its cookies and your server answers 401, which resolves normally. Safari content blockers do cause it.
The CSP case is covered in depth in the guide to games blocked by Content Security Policy, and the header setup in the CORS guide for CDNs.
Why it works on your domain and fails on a portal
On your own site the game and the API often share an origin, so CORS never applies. On a portal, everything about the page changes:
- The origin is the portal’s. The build is served from the portal’s domain or its CDN, inside an iframe. Every call to your backend is now cross-origin. Select the game’s frame in the DevTools console, run
location.origin, and allow that value on your API. - A sandboxed frame has no origin. If the iframe is sandboxed without
allow-same-origin, requests carryOrigin: null. An allowlist of named origins can never match it; onlyAccess-Control-Allow-Origin: *does, which rules out cookies. - Cookies are third-party. Session cookies for your API are blocked or partitioned in an embedded frame. Authenticate with a token in a header, and remember that a custom header triggers the preflight in the table above.
- The portal’s CSP applies to your game. A
connect-srcset in the portal’s response headers blocks hosts it does not list, and nothing in your build can override it. Some portals restrict or review external requests, so read their technical requirements before relying on your own backend, and prefer the portal SDK’s storage and leaderboards where they exist.
A CSP block is the one cause the page can detect directly:
document.addEventListener("securitypolicyviolation", function (event) {
console.warn("Blocked by CSP:", event.violatedDirective, event.blockedURI);
});
Requests that die when the page closes
An end-of-session save or analytics event sent with a plain fetch while the tab is closing is cancelled with the page. Send it when the page becomes hidden, which also fires on mobile when the player switches apps, and mark it to outlive the page:
document.addEventListener("visibilitychange", function () {
if (document.visibilityState !== "hidden") return;
fetch("/api/session-end", {
method: "POST",
keepalive: true,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ playtime: Math.round(performance.now() / 1000) })
}).catch(function () {});
});
keepalive requests are limited to 64 KiB of body in total, and a larger one fails with the same TypeError. navigator.sendBeacon(url, data) is the older equivalent: POST only, the same size limit, and no custom headers.
A safeFetch helper
This wrapper adds a timeout, retries requests that are safe to repeat with exponential backoff and jitter, and turns every outcome into one error type with a kind you can branch on. It also treats HTTP error statuses as failures, which bare fetch does not.
class FetchFailure extends Error {
constructor(kind, url, detail) {
super(kind + " failure for " + url + (detail ? " (" + detail + ")" : ""));
this.name = "FetchFailure";
this.kind = kind; // "network", "timeout", "http" or "aborted"
this.url = url;
this.status = kind === "http" ? detail : 0;
this.online = navigator.onLine;
}
}
const RETRY_STATUS = [408, 429, 500, 502, 503, 504];
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function safeFetch(url, options = {}) {
const { timeout = 8000, retries = 2, signal, ...init } = options;
const method = (init.method || "GET").toUpperCase();
const canRetry = ["GET", "HEAD", "PUT", "DELETE"].includes(method);
const maxAttempts = canRetry ? retries + 1 : 1;
let failure = null;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const controller = new AbortController();
let timedOut = false;
const timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeout);
const forward = () => controller.abort();
if (signal) {
if (signal.aborted) controller.abort();
else signal.addEventListener("abort", forward, { once: true });
}
try {
const response = await fetch(url, { ...init, signal: controller.signal });
if (response.ok) return response;
failure = new FetchFailure("http", url, response.status);
if (!RETRY_STATUS.includes(response.status)) throw failure;
} catch (err) {
if (err === failure) throw err; // an HTTP status not worth retrying
if (signal && signal.aborted) throw new FetchFailure("aborted", url);
failure = timedOut
? new FetchFailure("timeout", url, timeout + " ms")
: new FetchFailure("network", url, err && err.message);
} finally {
clearTimeout(timer);
if (signal) signal.removeEventListener("abort", forward);
}
if (attempt < maxAttempts) {
const cap = Math.min(8000, 500 * 2 ** (attempt - 1));
await sleep(cap / 2 + Math.random() * (cap / 2)); // backoff with jitter
}
}
throw failure;
}
POST is not retried, because a repeated score submission or purchase is worse than a failed one. Make such endpoints idempotent on the server (an idempotency key) before retrying them. The timeout covers the wait for the response headers; read the body inside your own try.
Keep the game running when a request fails
Decide per call what failure means for the player. Analytics, ads and leaderboards are optional: never await them in the path that starts a level, and swallow their failures.
function track(name, data) {
safeFetch("/api/events", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, data }),
timeout: 4000
}).catch(() => {}); // optional: failure must not reach the game loop
}
Saves are not optional, so the player has to see the state. Keep the newest unsent save, show a “connection lost” indicator, and try again later:
let pendingSave = null;
async function saveGame(state) {
pendingSave = state;
try {
await safeFetch("/api/save", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(state)
});
if (pendingSave === state) pendingSave = null;
showSaveStatus("saved");
} catch (err) {
showSaveStatus("offline"); // "Connection lost. Progress is kept on this device."
}
}
function retryPendingSave() {
if (pendingSave) saveGame(pendingSave);
}
window.addEventListener("online", retryPendingSave);
setInterval(retryPendingSave, 30000);
The timer is there because the online event is not enough. navigator.onLine being false reliably means offline, but true only means a network interface is up: a router with no uplink or a hotel login page still counts as online, and no event fires when real connectivity returns. Also write the save to localStorage or IndexedDB first, so a closed tab does not lose it.
Report it so it can be acted on
Thousands of reports titled TypeError: Failed to fetch cannot be triaged. Report the failure once per kind and host per session, with the facts the browser does let you read:
const reported = new Set();
function reportFetchFailure(err) {
const host = new URL(err.url, location.href).host;
const key = err.kind + " " + host;
if (reported.has(key)) return;
reported.add(key);
sendReport("Request failed: " + key, {
firstParty: host === location.host,
online: err.online,
visibility: document.visibilityState,
pageOrigin: location.origin,
secondsSinceLoad: Math.round(performance.now() / 1000)
});
}
The host and page origin separate “our API on the portal build” from “an ad host behind a blocker”. online: false and visibility: "hidden" explain most of the rest. Log the host, not the full URL, so tokens in query strings stay out of your reports.
How to confirm the fix
- In the DevTools Network tab, set throttling to Offline mid-game: the loop keeps running, the save indicator changes, and the save goes through after you switch back.
- Install a popular ad blocker and play a full session.
- Test the real portal build, in the portal’s iframe, in Chrome, Firefox and Safari.
- Close the tab during play and confirm the session-end request reached the server.
What a network failure looks like in Bugnet
If a rejected fetch is never caught, the Bugnet Web SDK receives it through its unhandledrejection listener and files it once per session, and the same title from other players stacks onto one entry. The browser gives the SDK no more than it gives you, so the report cannot say whether it was CORS, a blocker or a dead connection. It does carry the last 50 lines your game wrote to the console, which makes one console.warn with the host and navigator.onLine before you rethrow very useful, and Bugnet.reportBug(title, description, { category: "other" }) files the classified failure directly. One honest limit: reports are sent with fetch too. The SDK retries and holds reports while the browser is offline, but a player whose blocker stops the report host will not show up at all.
Related guides
- How to Fix Game Assets Blocked by CORS When Served From a CDN
- How to Fix a Web Game Blocked by Content Security Policy
- window.onerror vs unhandledrejection: Catching Every JavaScript Error in an HTML5 Game
- Crash Reporting for Web Games on Game Portals
- What Does “Script error.” Mean in a Web Game? (and How to Get the Real Error)
Frequently asked questions
What does TypeError: Failed to fetch mean?
The fetch request produced no response at all. It was blocked by the browser (CORS, mixed content, a Content-Security-Policy, an extension), cancelled, or it failed on the network. A server error such as 404 or 500 does not cause it, because those are responses and resolve normally.
Why does fetch not throw on a 404 or 500?
The fetch promise only rejects when no response arrives. Any HTTP status, including errors, resolves the promise. Check response.ok or response.status yourself and treat a false ok as a failure, or use a wrapper that does it for every request.
What are NetworkError when attempting to fetch resource and Load failed?
They are the same error in other browsers. Firefox reports TypeError: NetworkError when attempting to fetch resource and Safari reports TypeError: Load failed where Chrome reports TypeError: Failed to fetch. The causes and fixes are identical.
Why does my leaderboard work on my site but fail on a game portal?
On a portal the game runs on the portal’s origin inside an iframe, so calls to your backend become cross-origin and need a CORS header for that origin. The portal may also apply a Content-Security-Policy that blocks hosts it does not list, and cookies are treated as third-party.
How do I tell a timeout from a network failure in fetch?
Abort the request with an AbortController from a timer and record that the timer fired. An aborted fetch rejects with an AbortError DOMException, while a network or CORS failure rejects with a TypeError. Convert both into your own error type with a kind field.
The error message will never tell you why, so write the reason down yourself: classify every failure as network, timeout, http or aborted, and report the host and navigator.onLine with it.