How to Solve the "TypeError: Failed to execute 'fetch' on 'Window'" Error in JavaScript
The TypeError: Failed to execute 'fetch' on 'Window' is a common error that occurs when the fetch() request you are trying to make is malformed. The error message itself is quite generic, but it almost always points to a syntax error in the options object you passed to the fetch call, particularly within the headers.
This guide will walk you through a step-by-step process to debug and solve the common mistakes that cause this error, such as invalid characters in headers, incorrect header formatting, and providing a body for a GET request.
The Core Problem: A Malformed fetch Request
The fetch API is very strict about the format of its second argument, the options object. The TypeError is the browser's way of telling you that something in that object is syntactically incorrect according to the HTTP specification. While the error message is not very specific, it's almost always a problem with the headers.
Cause 1 (Most Common): Invalid Characters in Header Values
This is the most frequent cause of the error. HTTP headers cannot contain certain characters, and the most common offender is a newline character (\n). This often happens accidentally when copying a token or value from a terminal or a file that has a trailing newline.
Example of problem:
// Problem: The token string contains an invisible newline character at the end.
const myToken = 'your-secret-token\n';
fetch('https:/example.com/api/data', {
headers: {
// ⛔️ This will cause the TypeError because `myToken` has a newline.
'Authorization': `Bearer ${myToken}`
}
});
Solution: Always trim() your header values before using them, especially if they are coming from an external source, an environment variable, or user input. The String.prototype.trim() method removes whitespace (including newlines) from both the beginning and end of a string.
// ✅ Correct: Trim the token to remove any leading/trailing whitespace.
const myToken = 'your-secret-token\n'.trim();
fetch('https:/example.com/api/data', {
headers: {
'Authorization': `Bearer ${myToken}`
}
});
Cause 2: Incorrect Header Names or Format
The headers property itself must be an object, and the header names must be valid HTTP header strings without illegal characters like spaces or colons.
Example of problem: Incorrect Header Name
fetch('https:/example.com/api/data', {
headers: {
// ⛔️ Incorrect: The header name contains a space. It should be 'Content-Type'.
'Content Type': 'application/json'
}
});
Example of problem: Incorrect Header Format
fetch('https:/example.com/api/data', {
// ⛔️ Incorrect: `headers` must be an object, not a string.
headers: 'Authorization: Bearer my-token'
});
solution: ensure your headers property is a correctly formatted object with valid, correctly spelled header names.
// ✅ Correct: Headers is an object with valid, quoted key names.
fetch('https:/example.com/api/data', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer my-token'
}
});
Cause 3: Providing a body for a GET or HEAD Request
According to the HTTP specification, GET and HEAD requests cannot have a request body. If you provide a body property in the fetch options for these methods, the browser will throw an error.
Example of problem:
// Problem: A GET request with a `body`.
fetch('/api/data', {
method: 'GET',
// ⛔️ TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.
body: JSON.stringify({ id: 123 })
});
This will result in a more specific but related TypeError.
Solution: either remove the body property if you intended to make a GET request, or change the method to POST, PUT, or PATCH if you intended to send data.
A Correct fetch Example
This example shows a correctly structured POST request, which is the most common place to encounter these issues.
async function postData(url = '', data = {}) {
try {
const token = process.env.API_TOKEN.trim(); // Trim the token!
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Fetch error:', error);
}
}
Conclusion
The TypeError: Failed to execute 'fetch' is a syntax error that indicates a problem with the options you provided to the fetch call.
To solve it, carefully inspect your fetch options object and check for these common mistakes:
- Invalid Characters in Headers: This is the most common cause. Always
trim()your header values, especially authentication tokens, to remove hidden newline characters. - Incorrect Header Format: Ensure the
headersproperty is an object and that all header names are spelled correctly and contain no invalid characters. - Illegal Body: Do not provide a
bodyforGETorHEADrequests.