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.

Label: JavaScript Fetch API

Reference: Alex Devoro Blog

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; charset=utf-8

// 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'
  }
});

JavaScript Fetch API vs WordPress REST API

Label: JavaScript Fetch API vs WordPress REST API

Reference: TemplateArtist

The JavaScript Fetch API and the WordPress REST API are very different from one another, even though they are both APIs. Some of the differences include: 

  • The WordPress API returns data as JSON, whereas the Fetch API returns data as promises.
  • The Fetch API's data returned must be transformed into JSON using a.then handler.
  • The Fetch API allows you to return data in formats other than JSON.
  • You must write your promises after calling the WordPress REST API to use them.

You only need to call the fetch function in your JavaScript code to use the Fetch API with WordPress. To access the content, put a.then handler after that function. Then, you can make it visible on your website or in a web application.

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

Developers who have previously used the Fetch API on the front end will feel right at home using the built-in fetch() method in Node. It will be significantly simpler and more natural in a Node context than external packages.

Quicker implementation 

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.

No Additional Fetch Packages

With the release of Inbuilt Fetch for Node.js, other packages like node-fetch, got, cross-fetch, and others that served the same purpose may no longer exist. This implies you will not need to run an npm install before using Node to conduct network operations.

The most popular Node.js fetch package, node-fetch, recently switched to an ESM-only package. Therefore, it cannot be imported using the Node require() method. Due to the native Fetch API, HTTP fetching in Node settings will feel more natural and fluid.

Disadvantages

There are a few problems with the JavaScript Fetch API in the browser that will undoubtedly persist in the new Node.js 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. 

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

Label: Web browsers that support Fetch API

Reference: MSA Technosoft

Google Chrome

Fetch is not supported in Chrome versions 4 to 39. By turning on the "Experimental Web Platform Features" flag in chrome://flags, Chrome 40 and Chrome 41 can support Fetch. It is limited to a limited extent in Chrome and Opera within Windows and Workers. Fetchproperty is supported by Chrome 42–67.

Mozilla Firefox

Versions 2 through 33 of Mozilla Firefox do not support this element. When using Firefox 34 to 38, the ‘dom.fetch.enabled’ flag can enable this property, which is not supported by default. Firefox 39 to 61 supports Fetch.

Internet Explorer

Fetch is not supported by Internet Explorer 6 through 11.

Safari

Versions 3.1 through 10 of the Safari browser do not support Fetch. However, Fetch is compatible with Safari browser versions 10.1 to 11.

Microsoft Edge

Versions 12 through 13 of the Microsoft Edge browser do not support this property. But Fetch is supported on Edge 14 and 17.

Opera

Fetch is not supported by Opera versions 10.1 to 26. Opera versions 27 and 28 support the Fetch property partially. Turning on the "Experimental Web Platform Features" flag in chrome://flags makes these features accessible in Chrome and Opera within Windows and Workers. Opera versions 29 to 53 support Fetch.

What is JSON() in fetch?

The JSON response body is not directly returned by the simplest use of fetch(); instead, it returns a promise that resolves with a Response object. This use of fetch() only requires one argument, the path to the resource you want to fetch.

The Response object, on the other hand, represents the entire HTTP response and does not directly contain the JSON response body. Therefore, 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.

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

Reference: Morioh 

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.

Label: Fetch vs XMLHttpRequest 

Reference: YouTube

Firefox 39+, Opera 29+, and Chrome 42+ all support fetch. Microsoft has indicated that this feature is being considered. Ironically, a replacement for XMLHttpRequest appears just as Internet Explorer implements progress events for the response.

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