JavaScript Error
Failed to fetch
Chromium browsers show “Failed to fetch” when requests get no response. Usually CORS issues, ad blockers, or URL typos. Quick fixes: check URL, test in new tab, disable ad blockers.
This is how Chromium-based browsers (like Chrome, Microsoft Edge, or Brave) throw network errors when using the Fetch API. The uninspiring error message Failed to fetch
appears when the browser can’t get any response from the requested URL.
A certain amount of random network gremlins are to be expected on the internet, but this error can indicate a real problem with your web application that needs immediate attention.
Failed to Fetch is one of the most common JavaScript errors. It frequently ranks in the top 10 in the Global JavaScript Error Statistics.
Other browsers show similar errors with different messages:
- Safari:
Load failed
- Firefox:
NetworkError when attempting to fetch resource
- Axios Library:
Network Error
The Problem
This error is thrown by the Fetch API when the browser fails to get any response from the requested URL. The error will NOT occur if the server returns data, even a failed response like a 404 or 500 status code.
Something in your code is calling fetch()
and not getting a reply from the server. Here are typical examples that might trigger this error:
try {
const response = await fetch("https://api.example.com/data");
console.log(response.ok);
} catch (error) {
// Catching this gives us a chance to show users a more helpful message than just "Failed to fetch"
console.error("Fetch failed:", error.message);
}
Important: This error means the request never reached the server or the server never responded. It’s different from HTTP errors like 404 or 500, which indicate the server responded but with an error status.
Understanding the Root Cause
The “Failed to fetch” error can have several different causes, and identifying the right one is crucial for applying the correct fix. Here are the most common culprits:
1. CORS (Cross-Origin Resource Sharing) Issues
Most common cause: CORS is a browser security feature that blocks requests between different domains unless the server explicitly allows it. For example, a webpage on example.com
trying to fetch data from api.different-site.com
will be blocked unless the API server includes proper CORS headers.
How to identify: Check the browser console for additional CORS-related error messages alongside “Failed to fetch.”
2. Ad Blockers and Browser Extensions
Ad blockers are extremely common and will block requests to domains or URLs that match their filter lists. This affects a large percentage of your users.
How to identify: Test your application with ad blockers disabled. If the error disappears, ad blockers are the culprit.
3. Network Connectivity Issues
The server might be down, unreachable, or the URL might be incorrect.
Common scenarios:
- Server is offline or overloaded
- Wrong URL (typos, incorrect ports, missing protocols) — countless developer hours have been lost to debugging complex network issues that turned out to be a simple typo in the URL
- DNS resolution failures
- Firewall blocking the request
4. Page Navigation Aborting Requests
When users navigate away from a page, the browser cancels all pending fetch requests.
How to identify: These errors are usually sporadic and happen when users leave the page quickly.
5. Mixed Content Issues
Modern browsers block HTTP requests from HTTPS pages for security reasons.
How to identify: Check if you’re making HTTP requests from an HTTPS page.
6. Development Environment Issues
Common beginner mistakes:
- Trying to fetch from
localhost
when the API isn’t running - Wrong port numbers in development
- Missing API keys or authentication headers
- CORS issues that only appear in development
How to Fix “Failed to Fetch”
Quick Troubleshooting Checklist
- Check the URL for typos (protocols, ports, spelling)
- Verify the server/API is running and accessible
- Look for CORS error messages in browser console
- Test the URL directly in a new browser tab
- Temporarily disable ad blockers and browser extensions
- Check if you’re mixing HTTP and HTTPS requests
If the quick fixes don’t work, follow these detailed steps to debug and resolve the issue:
Step 1: Check the Browser DevTools
- Open DevTools (F12 or right-click → Inspect)
- Go to the Network tab
- Reproduce the error
- Look for your failed request - it will show as red or canceled
What to look for:
- Status: Failed, Canceled, or CORS error
- Response: Empty or error message
- Headers: Missing CORS headers or wrong content type
Step 2: Test the URL Directly
Copy the exact URL your code is trying to fetch and paste it into a new browser tab. This helps identify:
- Typos in the URL
- Server availability
- Authentication requirements
Step 3: Check for CORS Issues
If you see CORS-related messages in the console:
- The server needs to include proper CORS headers
- You might need a CORS proxy for development
- Consider using a server-side proxy instead of client-side requests
For development: Use a CORS proxy or configure your development server to allow CORS.
For production: Ensure your API server returns proper CORS headers:
// Example server-side CORS headers (Node.js/Express)
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'https://yourdomain.com');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});
Step 4: Implement Ad Blocker Fallbacks
Ad Blockers are just a fact of life on the internet. If your calls get blocked by these extensions, you’ll need to implement a fallback or workaround.
Handle ad blockers gracefully: Use first-party forwarding domains to route API requests through your own domain to avoid ad blocker detection. For example, use some-service.yourdomain.com to forward to a blocked some-service.com domain.
Implement fallback handling: When you can’t implement a first-party domain, you’ll need to accept that it may fail sometimes and implement a fallback, such as hiding the feature or showing a message.
async function fetchWithFallback(url) {
try {
const response = await fetch(url);
return response;
} catch (error) {
// Request failed, show a fallback message
}
}
Step 5: Add Proper Error Handling
Always wrap your fetch calls in try-catch blocks with comprehensive error handling:
async function safeFetch(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
if (error.message === 'Failed to fetch') {
console.error('Network error - check connection and CORS settings');
// Show user-friendly error message
} else {
console.error('Fetch error:', error.message);
}
throw error;
}
}
Step 6: Implement Retry Logic
For intermittent network issues, implement retry logic with exponential backoff:
async function fetchWithRetry(url, options = {}, maxRetries = 3) {
for (let i = 0; i <= maxRetries; i++) {
try {
const response = await fetch(url, options);
return response;
} catch (error) {
if (i === maxRetries) throw error;
// Wait before retrying (exponential backoff)
const delay = Math.pow(2, i) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
Step 7: Monitor and Log Errors
Don’t wait for users to report fetch errors - you need visibility into what’s happening in production. Error monitoring services like TrackJS automatically capture and report fetch failures across all your users’ browsers, giving you the data you need to identify patterns and fix issues before they impact more users.
Manual logging only captures errors you remember to add handlers for, but a comprehensive monitoring solution catches every “Failed to fetch” error along with the context needed to debug them effectively.
When to Ignore This Error
Failed to fetch
can sometimes be safely ignored:
- Page navigation errors: Users leaving the page before requests complete
- Ad blocker interference: If you have proper fallback handling
- Intermittent network issues: Occasional failures in mobile environments
However, you should investigate if:
- Errors are frequent or consistent
- They affect core functionality
- They correlate with user complaints
- They appear after code changes
Summary
The “Failed to fetch” error is common but manageable. Most cases are caused by CORS misconfiguration, ad blockers, or network connectivity issues. The key is implementing proper error handling, debugging systematically using browser DevTools, and providing good user feedback when requests fail.
Remember: This error means the request never reached the server or got no response back. It’s different from HTTP errors (404, 500) where the server actually responded with an error status.