Everything You Need To Know About The Browser JavaScript Fetch API

The JavaScript Fetch API sends and receives data between applications like all other APIs. The Fetch API is a modern interface that allows developers to make HTTP requests to servers from web browsers. Many people work with XMLHttpRequest (XHR) object, but the Fetch API can perform all the tasks the XHR object does. The JavaScript Fetch API is also much cleaner and simpler. It uses Promise to deliver more adaptable features for web browsers to send requests to servers.

JavaScript Fetch API

Fetch as a browser API

The fetch() method is available globally and instructs web browsers to send a request to a URL. The Fetch API can be accessed by simply passing a URL to the fetch function. This is a simple fetch GET request:

fetch("https://jsonplaceholder.typicode.com/users")

This will return a promise containing the information from the response. This response information includes methods for converting the raw response information to JSON, text, or other formats, as well as properties for the status.

fetch("https://jsonplaceholder.typicode.com/users").then(res => {
  console.log(res.ok) // true
  console.log(res.status) // 200
  return res.json()
})

The code above calls the JSON method on our response and returns that from the .then function. This is so that the JSON data from our response can be obtained from the promise that the JSON method also returns. We can then chain a second .then to get the data from the JSON method.

fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(data => console.log(data))
// [{ firstUser }, { secondUser }, ...]

Most of your fetch GETs will look like this when requesting data from a JSON API. The URL is fetched, the response is converted to JSON using the first .then, and the data in the final .then is used.

Response headers

The response contains a fetch header object that resembles a map that contains the response headers. Although it is not quite a map, it has methods that are comparable to a map to get specific headers by name or iterate over them:

let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits');
// get one header
alert(response.headers.get('Content-Type')); // application/json;
// iterate over all headers
for (let [key, value] of response.headers) {
  alert(`${key} = ${value}`);
}

Request headers

The fetch headers option can be used to set a request header. It has an object with outgoing headers that looks like this:

let response = fetch(protectedUrl, {
  headers: {
    Authentication: 'secret'
  }
});

Advantages and Disadvantages of JavaScript Fetch API

Advantages

The JavaScript Fetch API is now available as a pre-configured Node module to the developer community. The advantages of the Fetch API react are:

Cross-platform Familiarity
The same fetch syntax can be used across browsers, NodeJs, React and any javascript coding platform.

Quicker implementation

In NodeJs Undici is a quick, dependable, and spec-compliant Node.js HTTP client, and it is also the foundation of the new Fetch implementation. As a result, it is expected that the Fetch API will operate more effectively.

Promise Based Syntax
While some may disagree, it allows for a promise based syntax and avoids callback hell. This is quite relevant as making ajax calls is a very common operation.

Disadvantages

There are a few problems with the JavaScript Fetch API in the browser that will undoubtedly persist in the Fetch implementation:

Error Handling
Fetch API handles errors poorly and only treats network errors as true errors. This means that Fetch will only reject a promise if the user is not connected to the internet or if a rare networking error happens. Instead, Fetch will not take into account errors sent by the server. This can be confusing to many developers.

Establishing Timeouts
It is difficult to set timeouts in Fetch to cancel a particular request after a certain period of time elapses.

Lack of Request Progress
The fact that Fetch does not offer a simple way to track the status of requests, unlike libraries like Axios, is another important problem.

Web Browsers that support Fetch

Web browsers that support Fetch API

Fetch is now supported in major browsers and is also a part of NodeJs's native features.

What is JSON() in fetch?

When you call fetch, by default it resolves to an object which contains its response in text format in the data field. The JSON() call ensures that the response data is converted to a proper JSON object.

The Response object returned by fetch, represents the entire HTTP response and does not directly contain the JSON response body. We use the JSON() method, which returns a second promise that resolves with the outcome of parsing the response body text as JSON, to extract the JSON body content from the Response object.

JavaScript Fetch API vs REST API

The JavaScript Fetch API and the REST API are different from one another. Fetch is a browser utiltity that you would use to call a REST API. Some of the differences include:

  • Fetch is a function which takes a REST API url in its call.
  • REST APIs can accept headers like for Authentication but Fetch call be called by any javascript in the browser and in fact passes these headers while calling the REST APIs.

You only need to call the fetch function in your JavaScript code to use the Fetch API, it can be done from the browser or a server environment like from Node.js.

Is Fetch better than Ajax?

JavaScript Fetch API is a promise-based API used to retrieve resources from multiple web servers; it functions similarly to AJAX but has simpler syntax and more robust features.

Label: fetch vs Ajax

Without reloading, the JavaScript Fetch API can also send and receive data like XML, JSON, TEXT, and HTML from a web server. Fetch is also used to fetch data from Web APIs or REST APIs.

Below are the differences between Fetch and Ajax:

Properties

Fetch

Ajax ( XHR)

ECMA Version

ES6

ES5

Architecture

Promise based

Event-Based

Complexity

Easy

Complex

Syntax

Simple

Verbose

Request / Response

Supports

Supports but complex structure

Cookies

send cookies

Cookie less

Is Fetch better than XMLHttpRequest?

Like an XMLHttpRequest (XHR), the JavaScript Fetch API enables you to send network requests. The main difference is that the Fetch API react uses Promises, which allows for a simpler and cleaner API while avoiding callback hell and the need to recall the complex XMLHttpRequest API.

Fetch vs XMLHttpRequest

Fetch is now supported in all major browsers. If you like async/await syntax than you would love fetch. Even though XMLHttpRequest has been the goto way to make ajax calls on the web, it does require a slightly non intuitive syntax. Making web requests and managing responses is simpler with the fetch API than with an XMLHttpRequest.

Conclusion

The JavaScript Fetch API offers a more modern and intuitive way to request JavaScript HTTP than traditional XMLHttpRequest. While not fully supported in all browsers, its popularity is steadily growing, and developers can use polyfills to ensure broader compatibility. As the Fetch API continues to evolve and gain more comprehensive support, we can expect even more powerful and efficient features in the future.



How much is a great User Experience worth to you?


Browsee helps you understand your user's behaviour on your site. It's the next best thing to talking to them.

Browsee Product