Ask any question about JavaScript here... and get an instant response.
Why does my fetch request return a JSON parse error when the API response is empty?
Asked on Oct 29, 2025
Answer
When a fetch request returns an empty response, attempting to parse it as JSON will result in a JSON parse error because there is no content to parse. To handle this, you should first check if the response body is empty before parsing.
<!-- BEGIN COPY / PASTE -->
fetch('https://api.example.com/data')
.then(response => {
if (response.ok) {
return response.text().then(text => text ? JSON.parse(text) : {});
}
throw new Error('Network response was not ok.');
})
.then(data => {
console.log('Parsed data:', data);
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- This code first checks if the response is "ok" (status in the range 200-299).
- It then reads the response as text and checks if it's non-empty before parsing it as JSON.
- If the response is empty, it returns an empty object to avoid a parse error.
- Always handle errors using a catch block to manage any issues with the fetch operation.
Recommended Links:
