Get the Status Code of a Fetch HTTP Response in JavaScript

avatar

Borislav Hadzhiev

Sun Dec 26 20212 min read

banner

Photo by Shelby White

Get the Status Code of a Fetch HTTP Response #

To get the status code of an HTTP request made with the fetch method, access the status property on the response object. The response.status property contains the HTTP status code of the response, e.g. 200 for a successful response or 500 for a server error.

index.js
async function makeRequest() { try { const response = await fetch('https://randomuser.me/api/'); console.log('response.status: ', response.status); // 👉️ 200 console.log(response); } catch (err) { console.log(err); } } makeRequest();

We awaited the response from calling the fetch method and assigned the result to a response variable.

To get the status code of the HTTP response, access the status property on the response object.

Here is the same example, but using .then() and .catch() instead of async/await.

index.js
function makeRequest() { fetch('https://randomuser.me/api/') .then(response => { console.log('response.status: ', response.status); // 👉️ 200 console.log(response); }) .catch(err => { console.log(err); }); } makeRequest();

Note that the status property on the response object will only be populated for HTTP responses.

If the server doesn't respond at all, you encounter a CORS error or misspell the URL, you will get a network error, which would run the catch function and thestatus property would not be populated as it isn't a server HTTP response.

Here is a complete example of how you would go about handling requests and errors using fetch.

index.js
async function makeRequest() { try { const response = await fetch('https://randomuser.me/api/'); console.log('status code: ', response.status); // 👉️ 200 if (!response.ok) { console.log(response); throw new Error(`Error! status: ${response.status}`); } const result = await response.json(); return result; } catch (err) { console.log(err); } } makeRequest();

Notice that we use the response.ok property to check if the server responded with a status in the range of 200-299.

If the server's HTTP response was successful (200-299), the response.okproperty will have a value of true, otherwise false.

Because fetch doesn't reject the promise response for HTTP requests on its own, we have to check if the ok property was set to false - meaning the request was not successful and throw an error on our own.

If there is a network error, e.g. a CORS error or an error related to creating the HTTP request, the promise would get rejected automatically and our catchblock would get triggered.

As noted previously, if there is a network error, the status property will not be populated as the error did not come from an HTTP response from the server.

Use the search field on my Home Page to filter through my more than 1,000 articles.