Gathering detailed insights and metrics for whatwg-fetch
Gathering detailed insights and metrics for whatwg-fetch
Gathering detailed insights and metrics for whatwg-fetch
Gathering detailed insights and metrics for whatwg-fetch
isomorphic-fetch
Isomorphic WHATWG Fetch API, for Node & Browserify
cross-fetch
Universal WHATWG Fetch API for Node, Browsers and React Native
svix-fetch
An isomorphic WHATWG Fetch API, for Node & Browserify with keepalives
@applitools/isomorphic-fetch
Isomorphic WHATWG Fetch API, for Node & Browserify
npm install whatwg-fetch
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
25,759 Stars
715 Commits
2,843 Forks
621 Watching
2 Branches
72 Contributors
Updated on 27 Nov 2024
JavaScript (99.47%)
Makefile (0.53%)
Cumulative downloads
Total Downloads
Last day
-3.9%
2,482,422
Compared to previous day
Last week
3.5%
13,322,503
Compared to previous week
Last month
12.6%
54,444,493
Compared to previous month
Last year
-1.1%
608,203,402
Compared to previous year
The fetch()
function is a Promise-based mechanism for programmatically making
web requests in the browser. This project is a polyfill that implements a subset
of the standard Fetch specification, enough to make fetch
a viable
replacement for most uses of XMLHttpRequest in traditional web applications.
If you believe you found a bug with how fetch
behaves in your browser,
please don't open an issue in this repository unless you are testing in
an old version of a browser that doesn't support window.fetch
natively.
Make sure you read this entire readme, especially the Caveats
section, as there's probably a known work-around for an issue you've found.
This project is a polyfill, and since all modern browsers now implement the
fetch
function natively, no code from this project actually takes any
effect there. See Browser support for detailed
information.
If you have trouble making a request to another domain (a different subdomain or port number also constitutes another domain), please familiarize yourself with all the intricacies and limitations of CORS requests. Because CORS requires participation of the server by implementing specific HTTP response headers, it is often nontrivial to set up or debug. CORS is exclusively handled by the browser's internal mechanisms which this polyfill cannot influence.
This project doesn't work under Node.js environments. It's meant for web browsers only. You should ensure that your application doesn't try to package and run this on the server.
If you have an idea for a new feature of fetch
, submit your feature
requests to the specification's repository.
We only add features and APIs that are part of the Fetch specification.
npm install whatwg-fetch --save
You will also need a Promise polyfill for older browsers. We recommend taylorhakes/promise-polyfill for its small size and Promises/A+ compatibility.
Importing will automatically polyfill window.fetch
and related APIs:
1import 'whatwg-fetch' 2 3window.fetch(...)
If for some reason you need to access the polyfill implementation, it is available via exports:
1import {fetch as fetchPolyfill} from 'whatwg-fetch' 2 3window.fetch(...) // use native browser version 4fetchPolyfill(...) // use polyfill implementation
This approach can be used to, for example, use abort functionality in browsers that implement a native but outdated version of fetch that doesn't support aborting.
For use with webpack, add this package in the entry
configuration option
before your application entry point:
1entry: ['whatwg-fetch', ...]
1fetch('/users.html') 2 .then(function(response) { 3 return response.text() 4 }).then(function(body) { 5 document.body.innerHTML = body 6 })
1fetch('/users.json') 2 .then(function(response) { 3 return response.json() 4 }).then(function(json) { 5 console.log('parsed json', json) 6 }).catch(function(ex) { 7 console.log('parsing failed', ex) 8 })
1fetch('/users.json').then(function(response) { 2 console.log(response.headers.get('Content-Type')) 3 console.log(response.headers.get('Date')) 4 console.log(response.status) 5 console.log(response.statusText) 6})
1var form = document.querySelector('form') 2 3fetch('/users', { 4 method: 'POST', 5 body: new FormData(form) 6})
1fetch('/users', { 2 method: 'POST', 3 headers: { 4 'Content-Type': 'application/json' 5 }, 6 body: JSON.stringify({ 7 name: 'Hubot', 8 login: 'hubot', 9 }) 10})
1var input = document.querySelector('input[type="file"]') 2 3var data = new FormData() 4data.append('file', input.files[0]) 5data.append('user', 'hubot') 6 7fetch('/avatars', { 8 method: 'POST', 9 body: data 10})
The Promise returned from fetch()
won't reject on HTTP error status
even if the response is an HTTP 404 or 500. Instead, it will resolve normally,
and it will only reject on network failure or if anything prevented the
request from completing.
For maximum browser compatibility when it comes to sending & receiving
cookies, always supply the credentials: 'same-origin'
option instead of
relying on the default. See Sending cookies.
Not all Fetch standard options are supported in this polyfill. For instance,
redirect
and
cache
directives are ignored.
keepalive
is not supported because it would involve making a synchronous XHR, which is something this project is not willing to do. See issue #700 for more information.
To have fetch
Promise reject on HTTP error statuses, i.e. on any non-2xx
status, define a custom response handler:
1function checkStatus(response) { 2 if (response.status >= 200 && response.status < 300) { 3 return response 4 } else { 5 var error = new Error(response.statusText) 6 error.response = response 7 throw error 8 } 9} 10 11function parseJSON(response) { 12 return response.json() 13} 14 15fetch('/users') 16 .then(checkStatus) 17 .then(parseJSON) 18 .then(function(data) { 19 console.log('request succeeded with JSON response', data) 20 }).catch(function(error) { 21 console.log('request failed', error) 22 })
For CORS requests, use credentials: 'include'
to allow sending credentials
to other domains:
1fetch('https://example.com:1234/users', { 2 credentials: 'include' 3})
The default value for credentials
is "same-origin".
The default for credentials
wasn't always the same, though. The following
versions of browsers implemented an older version of the fetch specification
where the default was "omit":
If you target these browsers, it's advisable to always specify credentials: 'same-origin'
explicitly with all fetch requests instead of relying on the
default:
1fetch('/users', { 2 credentials: 'same-origin' 3})
Note: due to limitations of
XMLHttpRequest,
using credentials: 'omit'
is not respected for same domains in browsers where
this polyfill is active. Cookies will always be sent to same domains in older
browsers.
As with XMLHttpRequest, the Set-Cookie
response header returned from the
server is a forbidden header name and therefore can't be programmatically
read with response.headers.get()
. Instead, it's the browser's responsibility
to handle new cookies being set (if applicable to the current URL). Unless they
are HTTP-only, new cookies will be available through document.cookie
.
The Fetch specification defines these values for the redirect
option: "follow"
(the default), "error", and "manual".
Due to limitations of XMLHttpRequest, only the "follow" mode is available in browsers where this polyfill is active.
Due to limitations of XMLHttpRequest, the response.url
value might not be
reliable after HTTP redirects on older browsers.
The solution is to configure the server to set the response HTTP header
X-Request-URL
to the current URL after any redirect that might have happened.
It should be safe to set it unconditionally.
1# Ruby on Rails controller example 2response.headers['X-Request-URL'] = request.url
This server workaround is necessary if you need reliable response.url
in
Firefox < 32, Chrome < 37, Safari, or IE.
This polyfill supports the abortable fetch API. However, aborting a fetch requires use of two additional DOM APIs: AbortController and AbortSignal. Typically, browsers that do not support fetch will also not support AbortController or AbortSignal. Consequently, you will need to include an additional polyfill for these APIs to abort fetches:
1import 'yet-another-abortcontroller-polyfill' 2import {fetch} from 'whatwg-fetch' 3 4// use native browser implementation if it supports aborting 5const abortableFetch = ('signal' in new Request('')) ? window.fetch : fetch 6 7const controller = new AbortController() 8 9abortableFetch('/avatars', { 10 signal: controller.signal 11}).catch(function(ex) { 12 if (ex.name === 'AbortError') { 13 console.log('request aborted') 14 } 15}) 16 17// some time later... 18controller.abort()
Note: modern browsers such as Chrome, Firefox, Microsoft Edge, and Safari contain native
implementations of window.fetch
, therefore the code from this polyfill doesn't
have any effect on those browsers. If you believe you've encountered an error
with how window.fetch
is implemented in any of these browsers, you should file
an issue with that browser vendor instead of this project.
No vulnerabilities found.
Reason
security policy file detected
Details
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
Found 3/4 approved changesets -- score normalized to 7
Reason
dependency not pinned by hash detected -- score normalized to 7
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More