Fix JavaScript 'TypeError: Failed to fetch' in Browser & Node.js
Diagnose network drops, CORS blocks, HTTPS certificate invalidity, and ad-blocker request cancellations.
TypeError: Failed to fetch (at window.fetch)
async function safeFetch() {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10s timeout
try {
const res = await fetch("https://api.example.com/v1", {
signal: controller.signal,
headers: { "Content-Type": "application/json" }
});
if (!res.ok) throw new Error(`Server returned ${res.status}`);
return await res.json();
} catch (err: any) {
if (err.name === "AbortError") {
console.error("Request timed out after 10s");
} else {
console.error("Network or CORS failure:", err.message);
}
throw err;
} finally {
clearTimeout(timeoutId);
}
}Root Cause & Mechanism Analysis
Why does this error occur?
Generic browser error thrown when a network request fails before receiving an HTTP response: triggered by CORS preflight rejections, DNS resolution failures, offline network, or mixed content (HTTP on HTTPS).
Frequently Asked Questions
Why doesn't fetch reject on 404 or 500 status?
Related Developer Error Solutions
Browse All 35 GuidesCORS 'Access-Control-Allow-Origin' Missing
Resolve browser cross-origin resource sharing errors by configuring backend HTTP headers and handling preflight OPTIONS requests.
SSL: NET::ERR_CERT_AUTHORITY_INVALID
Resolve SSL/TLS certificate trust errors in development, curl, Node.js, and local HTTPS environments.
Nginx 502 Bad Gateway
Resolve reverse proxy gateway errors when Nginx cannot establish a connection with Node.js, Next.js, or Gunicorn backends.