Today I learned

Fetch API response.ok

Edit this Post Opens in new tab

Today I learned that the fetch API does only reject on a Network error or when CORS is misconfigured on the server-side. This means requests which responed with a 4xx or a 5xx status code are also treated as successful and won't be rejected.

There is an additional .ok method on the response you can check for true

So the best way to check, if a fetch request is actually successful, includes checking if the promise resolved, then checking if the response.ok property holds a value of true.

Here is an example which illustrates this:

fetch(url)
  .then((response) => {
    if (!response.ok) {
      throw new Error('Network response was not ok')
    }
    return response.json()
  })
  .then((responseJSON) => {
    // do something with the response
  })
  .catch((error) => {
    console.error('There has been a problem with your fetch operation:', error)
  })

To learn more about this and the Fetch API in general, check out the MDN docs Opens in new tab article about using fetch.


I hope you enjoyed this post and learned something new. If you have any questions, feel free to reach out to me on Twitter Opens in new tab or via Email Opens in new tab.

If you want to support me, you can buy me a coffee. I would be very happy about it!

☕️ Buy me a coffee ☕️

I wish you a wonderful day! Marco