When making network requests in JavaScript using the fetch() API, developers often chain .json() to automatically parse the response. But what happens if the server returns an empty response (like an HTTP 204 No Content) or crashes mid-stream?
You get the dreaded SyntaxError: fetch unexpected end of json input.
Why fetching throws this error
The .json() method on a Response object attempts to read the body stream to completion and instantly run it through JSON.parse(). If the body is completely empty (""), it fails because an empty string is not valid JSON.
To see an in-depth breakdown of how JSON.parse() behaves under the hood, read our massive guide on How to fix Unexpected End of JSON Input.
// BAD CODE: Blindly assuming the response has JSON
const response = await fetch('/api/delete-user', { method: 'DELETE' });
const data = await response.json(); // Crashes if the server sends HTTP 204 (No Content)
The Safe Fetch Wrapper
To prevent this, you must check the HTTP status code (or check if the response literally has content) before extracting the JSON.
If you aren’t sure what the payload looks like, grab the raw text using response.text() and drop it into a secure JSON Validator to ensure it is actually structured correctly.
// GOOD CODE: Safe JSON parsing
const response = await fetch('/api/data');
// 1. Check if the network call succeeded entirely
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// 2. Check if the server actually sent content (Status 204 means No Content)
if (response.status === 204 || response.headers.get('content-length') === '0') {
return null; // Stop early, don't parse!
}
// 3. Only now is it safe to parse
const data = await response.json();
Related Errors
If you fixed the “unexpected end” issue but are now seeing an entirely different character crash your app, you might be dealing with the wrong content type.
For instance, receiving an HTML error page instead of an API payload will trigger a < token error. Learn how to debug that in our Unexpected Token Guide. Similarly, if you are working with local files rather than APIs, ensure your file isn’t corrupted by checking our tutorial on How to Open JSON Files.