How to Get the Status Code of a Fetch HTTP Response in JavaScript

Updated onbyAlan Morel
How to Get the Status Code of a Fetch HTTP Response in JavaScript

When you make a request on the web, the status code is what lets you know the status of the response.

This is useful because when you know the request failed, you can handle the error accordingly, or proceed with the data if the request was successful.

In this post, we will look at how to get the status code of a response when using the Fetch API in JavaScript.

How to get the status code of a response

To get the status code of a response, first let's make a request:

JAVASCRIPT
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");

Then, we can get the status code of the response by accessing the status property:

JAVASCRIPT
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1"); const statusCode = response.status;

If the request was successful, the status code will be 200.

Alternatively, you can check for response.ok which will return a boolean for you if the status code is between 200 and 299.

JAVASCRIPT
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1"); const isSuccessful = response.ok; if (isSuccessful) { // do something }

Once successful, you can get the JSON, text, or blob data from the response:

JAVASCRIPT
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1"); const isSuccessful = response.ok; if (isSuccessful) { const data = await response.json(); // do something with the data }

To play it safe, you could wrap all your code inside a try/catch block:

JAVASCRIPT
try { const response = await fetch("https://jsonplaceholder.typicode.com/posts/1"); const isSuccessful = response.ok; if (isSuccessful) { const data = await response.json(); // do something with the data } } catch (error) { // handle the error }

Conclusion

In this post, we looked at how to get the status code of a response when using the Fetch API in JavaScript.

Simply call the status property on the response object to get the status code.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.