278

I know that Fetch API uses Promises and both of them allow you to do AJAX requests to a server.

I have read that Fetch API has some extra features, which aren't available in XMLHttpRequest (and in the Fetch API polyfill, since it's based on XHR).

What extra capabilities does the Fetch API have?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
ilyabasiuk
  • 4,270
  • 4
  • 22
  • 35
  • 3
    Though I can't recall on the spot, there are one or two things you can do with XHR you can't with fetch. You say you have read that fetch has extra possibilities, those articles aren't very good if they don't say what they are – Jaromanda X Feb 22 '16 at 09:09
  • 8
    found the two things you can't do with fetch that you can with XHR ... you can't set your own value for request timeout in fetch, nor can you get progress events – Jaromanda X Feb 22 '16 at 09:12
  • 4
    Fetch is just a simplified way of doing things for most types of XMLHttpRequests. If your use case fits what Fetch does, then use it. When you get right down to it the XMLHttpRequest API is ugly for what most people use it for. Fetch was an effort to offer a cleaner way of doing things that doesn't need a library wrapped around XMLHttpRequest to make it palatable. – jfriend00 Feb 22 '16 at 09:17
  • 1
    It has pure support in browsers ( http://caniuse.com/#search=fetch ), so there is a polifill for it https://github.com/github/fetch, wich is working above xhr – ilyabasiuk Feb 22 '16 at 11:23
  • 2
    @jfriend00, that's incorrect, fetch is not a simplified way, but a more low-level way (indeed, XHR is now defined in terms of Fetch: https://xhr.spec.whatwg.org/#the-send%28%29-method). – Marco Castelluccio Feb 22 '16 at 11:28
  • 4
    @Marco - How can you not say that `fetch(url).then(function(data) (...));` is not simpler than using `XMLHttpRequest` to do the same thing? It may have lots of other features, but geez, it sure is simpler to use for common things. It IS a cleaned up API. – jfriend00 Feb 22 '16 at 16:13
  • 2
    Wait, I'm not saying it isn't simpler. I'm saying that your comment was incorrect, because you said "fetch is JUST a simplified way ...", this makes people think, incorrectly, that fetch doesn't have more features than XMLHttpRequest. – Marco Castelluccio Feb 22 '16 at 16:32
  • Fetch is not a simplified way of XHR. It's sort of more complicated. You can't even reuse the response text/object without relying on the `.clone()` voodoo that itself is a complicated promise-based method compared to XHR's straightforward approach. – KHAYRI R.R. WOULFE Nov 07 '22 at 05:43

3 Answers3

191

There are a few things that you can do with fetch and not with XHR:

  • You can use the Cache API with the request and response objects;
  • You can perform no-cors requests, getting a response from a server that doesn't implement CORS. You can't access the response body directly from JavaScript, but you can use it with other APIs (e.g. the Cache API);
  • Streaming responses (with XHR the entire response is buffered in memory, with fetch you will be able to access the low-level stream). This isn't available yet in all browsers, but will be soon.

There are a couple of things that you can do with XHR that you can't do yet with fetch, but they're going to be available sooner or later (read the "Future improvements" paragraph here: https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/):

  • Abort a request (this now works in Firefox and Edge, as @sideshowbarker explains in his comment);
  • Report progress.

This article https://jakearchibald.com/2015/thats-so-fetch/ contains a more detailed description.

Marco Castelluccio
  • 10,152
  • 2
  • 33
  • 48
  • 2
    The spec for the Fetch API now provides for cancellation. Support has so far shipped in Firefox 57 and Edge 16. Demos: https://fetch-abort-demo-edge.glitch.me/, https://mdn.github.io/dom-examples/abort-api/. And there are open Chrome & Webkit feature bugs https://bugs.chromium.org/p/chromium/issues/detail?id=750599, https://bugs.webkit.org/show_bug.cgi?id=174980. How-to: https://developers.google.com/web/updates/2017/09/abortable-fetch, https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal#Examples. And example in the Stack Overflow answer at https://stackoverflow.com/a/47250621/441757 – sideshowbarker Dec 10 '17 at 07:04
  • 3
    Another difference is that `fetch` requests can't be replayed on Developer Tools. – Parziphal Jun 21 '18 at 21:58
  • 2
    And, from my experience, `fetch` can request for files, but XHR can't. – D. Pardal Aug 27 '18 at 09:30
  • 3
    Reporting in 2021, still no way to track progress for requests (or responses) created with the `fetch` API. `XMLHttpRequest` thus dies a slow agonising death, if at all. – Armen Michaeli Feb 12 '21 at 16:36
  • 1
    is there any speed difference in requesting and getting back the request or are they the same in performance ? – strix25 Apr 14 '22 at 11:27
  • 1
    What's a Cache api? – Shad Jun 07 '22 at 11:14
  • You can't bypass CORS using `fetch()`. – KHAYRI R.R. WOULFE Nov 07 '22 at 05:44
99

fetch

  • missing a builtin method to consume documents
  • no way to set a timeout yet
  • can't override the content-type response header
  • if the content-length response header is present but not exposed, the body's total length is unknown during the streaming
  • will call the signal's abort handler even if the request has been completed
  • no upload progress (support for ReadableStream instances as request bodies is yet to come)
  • doesn't support --allow-file-access-from-files (chromium)

XHR

  • there's no way to not send cookies (apart from using the non-standard mozAnon flag or the AnonXMLHttpRequest constructor)
  • can't return FormData instances
  • doesn't have an equivalent to fetch's no-cors mode
  • always follows redirects
Artur INTECH
  • 6,024
  • 2
  • 37
  • 34
Knu
  • 14,806
  • 5
  • 56
  • 89
  • 20
    `fetch` is also missing progress. with XHR you can track progress with the `progress` event – MayThrow Aug 22 '17 at 23:35
  • 2
    "can't override the content-type header of the response"... this is just a bad idea to begin with. the 'content-type dictates what is to be returned and the BACKEND SHOULD dictate that to the frontend. IN FACT, content-type should be the 'ONLY HEADER' for type because what is requested, is what should be returned. If you want something different serve from a special subdomain or something so you can handles specific functionality separate. You ar trying to force a 1% rule down 99% of everyones throat. – Orubel Jan 16 '18 at 00:38
  • @Knu yep and now we are more advanced and we can easily automate a 90% solution and let the freak cases route to different functionality. – Orubel Jan 17 '18 at 22:39
  • 1
    @rzr not exactly, you got `Response#body`. – Knu Sep 06 '18 at 17:21
  • Granted, [it doesn't look like `no-cors` is that useful anyway](https://stackoverflow.com/a/43268098/1874170)... – JamesTheAwesomeDude Apr 28 '21 at 18:06
23

The answers above are good and provide good insights, but I share the same opinion as shared in this google developers blog entry in that the main difference (from a practical perspective) is the convenience of the built-in promise returned from fetch

Instead of having to write code like this

function reqListener() {
    var data = JSON.parse(this.responseText);
}

function reqError(err) { ... }

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.onerror = reqError;
oReq.open('get', './api/some.json', true);
oReq.send();

we can clean things up and write something a little more concise and readable with promises and modern syntax

fetch('./api/some.json')
    .then((response) => {
        response.json().then((data) => { 
            ... 
        });
    })
    .catch((err) => { ... });
Felipe
  • 10,606
  • 5
  • 40
  • 57
  • 9
    @TheOpti You can polyfill basic fetch support into IE 11. You could also just drop IE11 as a supported browser in many projects as in many user bases IE 11 usage is now below 1%. – Devon Holcombe Apr 16 '18 at 18:38
  • I hate IE but I also don't recommend dropping IE support especially when there are polyfills. Millions of people still use IE and other old browsers. Just a few days ago I had to tell a client not to use IE after I saw him using it. Of course if your project is not going to support IE anyway then a polyfill won't help. – PHP Guru Dec 15 '20 at 04:31
  • @PHPGuru grr! This pisses me off. **All the latest web technologies are fully unavailable on Internet Explorer.** I wish people would switch to Microsoft Edge, at the very least! And I wish MS would issue an "update" to IE which would disable the browser entirely (or show a nag screen before allowing use) and tell people to switch to another browser. – ADTC Oct 06 '21 at 13:16
  • I think it's pure marketing on Microsoft's part. If they leave IE on computers that have Edge installed on them, then their hope is that people will think that Edge is a different browser (it's not) and IE's bad reputation will die with IE. The only difference is that Edge is newer than IE. But if you don't make sure you have the latest version of Edge, you might as well be using IE. – PHP Guru Oct 25 '21 at 06:57
  • 3
    @PHPGuru As someone who worked for a couple of years in a team where we needed IE11 support I can tell you 100% that even the Edge that was based on IE code was very different and better to work with than IE11, which was a nightmare. What's more the new Edge that is based on Chromium, and essentially just a repackaging of Chrome, was released in January 2020, over a year before you wrote this comment. Really weird to me that people still repeat this FUD that Edge is just IE – ChrisM Jan 10 '22 at 07:47
  • I was talking about old versions of Edge which I found out I still had on my Windows 10 PC when I wrote that comment. As a result I realized it wasn't supporting the new standards, features and security updates we take for granted now, until I made sure I had the latest version. – PHP Guru Feb 09 '22 at 16:05