| 1 | # window.fetch polyfill |
| 2 | |
| 3 | The `fetch()` function is a Promise-based mechanism for programmatically making |
| 4 | web requests in the browser. This project is a polyfill that implements a subset |
| 5 | of the standard [Fetch specification][], enough to make `fetch` a viable |
| 6 | replacement for most uses of XMLHttpRequest in traditional web applications. |
| 7 | |
| 8 | ## Table of Contents |
| 9 | |
| 10 | * [Read this first](#read-this-first) |
| 11 | * [Installation](#installation) |
| 12 | * [Usage](#usage) |
| 13 | * [Importing](#importing) |
| 14 | * [HTML](#html) |
| 15 | * [JSON](#json) |
| 16 | * [Response metadata](#response-metadata) |
| 17 | * [Post form](#post-form) |
| 18 | * [Post JSON](#post-json) |
| 19 | * [File upload](#file-upload) |
| 20 | * [Caveats](#caveats) |
| 21 | * [Handling HTTP error statuses](#handling-http-error-statuses) |
| 22 | * [Sending cookies](#sending-cookies) |
| 23 | * [Receiving cookies](#receiving-cookies) |
| 24 | * [Redirect modes](#redirect-modes) |
| 25 | * [Obtaining the Response URL](#obtaining-the-response-url) |
| 26 | * [Aborting requests](#aborting-requests) |
| 27 | * [Browser Support](#browser-support) |
| 28 | |
| 29 | ## Read this first |
| 30 | |
| 31 | * If you believe you found a bug with how `fetch` behaves in your browser, |
| 32 | please **don't open an issue in this repository** unless you are testing in |
| 33 | an old version of a browser that doesn't support `window.fetch` natively. |
| 34 | Make sure you read this _entire_ readme, especially the [Caveats](#caveats) |
| 35 | section, as there's probably a known work-around for an issue you've found. |
| 36 | This project is a _polyfill_, and since all modern browsers now implement the |
| 37 | `fetch` function natively, **no code from this project** actually takes any |
| 38 | effect there. See [Browser support](#browser-support) for detailed |
| 39 | information. |
| 40 | |
| 41 | * If you have trouble **making a request to another domain** (a different |
| 42 | subdomain or port number also constitutes another domain), please familiarize |
| 43 | yourself with all the intricacies and limitations of [CORS][] requests. |
| 44 | Because CORS requires participation of the server by implementing specific |
| 45 | HTTP response headers, it is often nontrivial to set up or debug. CORS is |
| 46 | exclusively handled by the browser's internal mechanisms which this polyfill |
| 47 | cannot influence. |
| 48 | |
| 49 | * This project **doesn't work under Node.js environments**. It's meant for web |
| 50 | browsers only. You should ensure that your application doesn't try to package |
| 51 | and run this on the server. |
| 52 | |
| 53 | * If you have an idea for a new feature of `fetch`, **submit your feature |
| 54 | requests** to the [specification's repository](https://github.com/whatwg/fetch/issues). |
| 55 | We only add features and APIs that are part of the [Fetch specification][]. |
| 56 | |
| 57 | ## Installation |
| 58 | |
| 59 | ``` |
| 60 | npm install whatwg-fetch --save |
| 61 | ``` |
| 62 | |
| 63 | As an alternative to using npm, you can obtain `fetch.umd.js` from the |
| 64 | [Releases][] section. The UMD distribution is compatible with AMD and CommonJS |
| 65 | module loaders, as well as loading directly into a page via `<script>` tag. |
| 66 | |
| 67 | You will also need a Promise polyfill for [older browsers](http://caniuse.com/#feat=promises). |
| 68 | We recommend [taylorhakes/promise-polyfill](https://github.com/taylorhakes/promise-polyfill) |
| 69 | for its small size and Promises/A+ compatibility. |
| 70 | |
| 71 | ## Usage |
| 72 | |
| 73 | For a more comprehensive API reference that this polyfill supports, refer to |
| 74 | https://github.github.io/fetch/. |
| 75 | |
| 76 | ### Importing |
| 77 | |
| 78 | Importing will automatically polyfill `window.fetch` and related APIs: |
| 79 | |
| 80 | ```javascript |
| 81 | import 'whatwg-fetch' |
| 82 | |
| 83 | window.fetch(...) |
| 84 | ``` |
| 85 | |
| 86 | If for some reason you need to access the polyfill implementation, it is |
| 87 | available via exports: |
| 88 | |
| 89 | ```javascript |
| 90 | import {fetch as fetchPolyfill} from 'whatwg-fetch' |
| 91 | |
| 92 | window.fetch(...) // use native browser version |
| 93 | fetchPolyfill(...) // use polyfill implementation |
| 94 | ``` |
| 95 | |
| 96 | This approach can be used to, for example, use [abort |
| 97 | functionality](#aborting-requests) in browsers that implement a native but |
| 98 | outdated version of fetch that doesn't support aborting. |
| 99 | |
| 100 | For use with webpack, add this package in the `entry` configuration option |
| 101 | before your application entry point: |
| 102 | |
| 103 | ```javascript |
| 104 | entry: ['whatwg-fetch', ...] |
| 105 | ``` |
| 106 | |
| 107 | ### HTML |
| 108 | |
| 109 | ```javascript |
| 110 | fetch('/users.html') |
| 111 | .then(function(response) { |
| 112 | return response.text() |
| 113 | }).then(function(body) { |
| 114 | document.body.innerHTML = body |
| 115 | }) |
| 116 | ``` |
| 117 | |
| 118 | ### JSON |
| 119 | |
| 120 | ```javascript |
| 121 | fetch('/users.json') |
| 122 | .then(function(response) { |
| 123 | return response.json() |
| 124 | }).then(function(json) { |
| 125 | console.log('parsed json', json) |
| 126 | }).catch(function(ex) { |
| 127 | console.log('parsing failed', ex) |
| 128 | }) |
| 129 | ``` |
| 130 | |
| 131 | ### Response metadata |
| 132 | |
| 133 | ```javascript |
| 134 | fetch('/users.json').then(function(response) { |
| 135 | console.log(response.headers.get('Content-Type')) |
| 136 | console.log(response.headers.get('Date')) |
| 137 | console.log(response.status) |
| 138 | console.log(response.statusText) |
| 139 | }) |
| 140 | ``` |
| 141 | |
| 142 | ### Post form |
| 143 | |
| 144 | ```javascript |
| 145 | var form = document.querySelector('form') |
| 146 | |
| 147 | fetch('/users', { |
| 148 | method: 'POST', |
| 149 | body: new FormData(form) |
| 150 | }) |
| 151 | ``` |
| 152 | |
| 153 | ### Post JSON |
| 154 | |
| 155 | ```javascript |
| 156 | fetch('/users', { |
| 157 | method: 'POST', |
| 158 | headers: { |
| 159 | 'Content-Type': 'application/json' |
| 160 | }, |
| 161 | body: JSON.stringify({ |
| 162 | name: 'Hubot', |
| 163 | login: 'hubot', |
| 164 | }) |
| 165 | }) |
| 166 | ``` |
| 167 | |
| 168 | ### File upload |
| 169 | |
| 170 | ```javascript |
| 171 | var input = document.querySelector('input[type="file"]') |
| 172 | |
| 173 | var data = new FormData() |
| 174 | data.append('file', input.files[0]) |
| 175 | data.append('user', 'hubot') |
| 176 | |
| 177 | fetch('/avatars', { |
| 178 | method: 'POST', |
| 179 | body: data |
| 180 | }) |
| 181 | ``` |
| 182 | |
| 183 | ### Caveats |
| 184 | |
| 185 | * The Promise returned from `fetch()` **won't reject on HTTP error status** |
| 186 | even if the response is an HTTP 404 or 500. Instead, it will resolve normally, |
| 187 | and it will only reject on network failure or if anything prevented the |
| 188 | request from completing. |
| 189 | |
| 190 | * For maximum browser compatibility when it comes to sending & receiving |
| 191 | cookies, always supply the `credentials: 'same-origin'` option instead of |
| 192 | relying on the default. See [Sending cookies](#sending-cookies). |
| 193 | |
| 194 | * Not all Fetch standard options are supported in this polyfill. For instance, |
| 195 | [`redirect`](#redirect-modes) and |
| 196 | [`cache`](https://github.github.io/fetch/#caveats) directives are ignored. |
| 197 | |
| 198 | * `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](https://github.com/github/fetch/issues/700#issuecomment-484188326) for more information. |
| 199 | |
| 200 | #### Handling HTTP error statuses |
| 201 | |
| 202 | To have `fetch` Promise reject on HTTP error statuses, i.e. on any non-2xx |
| 203 | status, define a custom response handler: |
| 204 | |
| 205 | ```javascript |
| 206 | function checkStatus(response) { |
| 207 | if (response.status >= 200 && response.status < 300) { |
| 208 | return response |
| 209 | } else { |
| 210 | var error = new Error(response.statusText) |
| 211 | error.response = response |
| 212 | throw error |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | function parseJSON(response) { |
| 217 | return response.json() |
| 218 | } |
| 219 | |
| 220 | fetch('/users') |
| 221 | .then(checkStatus) |
| 222 | .then(parseJSON) |
| 223 | .then(function(data) { |
| 224 | console.log('request succeeded with JSON response', data) |
| 225 | }).catch(function(error) { |
| 226 | console.log('request failed', error) |
| 227 | }) |
| 228 | ``` |
| 229 | |
| 230 | #### Sending cookies |
| 231 | |
| 232 | For [CORS][] requests, use `credentials: 'include'` to allow sending credentials |
| 233 | to other domains: |
| 234 | |
| 235 | ```javascript |
| 236 | fetch('https://example.com:1234/users', { |
| 237 | credentials: 'include' |
| 238 | }) |
| 239 | ``` |
| 240 | |
| 241 | The default value for `credentials` is "same-origin". |
| 242 | |
| 243 | The default for `credentials` wasn't always the same, though. The following |
| 244 | versions of browsers implemented an older version of the fetch specification |
| 245 | where the default was "omit": |
| 246 | |
| 247 | * Firefox 39-60 |
| 248 | * Chrome 42-67 |
| 249 | * Safari 10.1-11.1.2 |
| 250 | |
| 251 | If you target these browsers, it's advisable to always specify `credentials: |
| 252 | 'same-origin'` explicitly with all fetch requests instead of relying on the |
| 253 | default: |
| 254 | |
| 255 | ```javascript |
| 256 | fetch('/users', { |
| 257 | credentials: 'same-origin' |
| 258 | }) |
| 259 | ``` |
| 260 | |
| 261 | Note: due to [limitations of |
| 262 | XMLHttpRequest](https://github.com/github/fetch/pull/56#issuecomment-68835992), |
| 263 | using `credentials: 'omit'` is not respected for same domains in browsers where |
| 264 | this polyfill is active. Cookies will always be sent to same domains in older |
| 265 | browsers. |
| 266 | |
| 267 | #### Receiving cookies |
| 268 | |
| 269 | As with XMLHttpRequest, the `Set-Cookie` response header returned from the |
| 270 | server is a [forbidden header name][] and therefore can't be programmatically |
| 271 | read with `response.headers.get()`. Instead, it's the browser's responsibility |
| 272 | to handle new cookies being set (if applicable to the current URL). Unless they |
| 273 | are HTTP-only, new cookies will be available through `document.cookie`. |
| 274 | |
| 275 | #### Redirect modes |
| 276 | |
| 277 | The Fetch specification defines these values for [the `redirect` |
| 278 | option](https://fetch.spec.whatwg.org/#concept-request-redirect-mode): "follow" |
| 279 | (the default), "error", and "manual". |
| 280 | |
| 281 | Due to limitations of XMLHttpRequest, only the "follow" mode is available in |
| 282 | browsers where this polyfill is active. |
| 283 | |
| 284 | #### Obtaining the Response URL |
| 285 | |
| 286 | Due to limitations of XMLHttpRequest, the `response.url` value might not be |
| 287 | reliable after HTTP redirects on older browsers. |
| 288 | |
| 289 | The solution is to configure the server to set the response HTTP header |
| 290 | `X-Request-URL` to the current URL after any redirect that might have happened. |
| 291 | It should be safe to set it unconditionally. |
| 292 | |
| 293 | ``` ruby |
| 294 | # Ruby on Rails controller example |
| 295 | response.headers['X-Request-URL'] = request.url |
| 296 | ``` |
| 297 | |
| 298 | This server workaround is necessary if you need reliable `response.url` in |
| 299 | Firefox < 32, Chrome < 37, Safari, or IE. |
| 300 | |
| 301 | #### Aborting requests |
| 302 | |
| 303 | This polyfill supports |
| 304 | [the abortable fetch API](https://developers.google.com/web/updates/2017/09/abortable-fetch). |
| 305 | However, aborting a fetch requires use of two additional DOM APIs: |
| 306 | [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) and |
| 307 | [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal). |
| 308 | Typically, browsers that do not support fetch will also not support |
| 309 | AbortController or AbortSignal. Consequently, you will need to include |
| 310 | [an additional polyfill](https://www.npmjs.com/package/yet-another-abortcontroller-polyfill) |
| 311 | for these APIs to abort fetches: |
| 312 | |
| 313 | ```js |
| 314 | import 'yet-another-abortcontroller-polyfill' |
| 315 | import {fetch} from 'whatwg-fetch' |
| 316 | |
| 317 | // use native browser implementation if it supports aborting |
| 318 | const abortableFetch = ('signal' in new Request('')) ? window.fetch : fetch |
| 319 | |
| 320 | const controller = new AbortController() |
| 321 | |
| 322 | abortableFetch('/avatars', { |
| 323 | signal: controller.signal |
| 324 | }).catch(function(ex) { |
| 325 | if (ex.name === 'AbortError') { |
| 326 | console.log('request aborted') |
| 327 | } |
| 328 | }) |
| 329 | |
| 330 | // some time later... |
| 331 | controller.abort() |
| 332 | ``` |
| 333 | |
| 334 | ## Browser Support |
| 335 | |
| 336 | - Chrome |
| 337 | - Firefox |
| 338 | - Safari 6.1+ |
| 339 | - Internet Explorer 10+ |
| 340 | |
| 341 | Note: modern browsers such as Chrome, Firefox, Microsoft Edge, and Safari contain native |
| 342 | implementations of `window.fetch`, therefore the code from this polyfill doesn't |
| 343 | have any effect on those browsers. If you believe you've encountered an error |
| 344 | with how `window.fetch` is implemented in any of these browsers, you should file |
| 345 | an issue with that browser vendor instead of this project. |
| 346 | |
| 347 | |
| 348 | [fetch specification]: https://fetch.spec.whatwg.org |
| 349 | [cors]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS |
| 350 | "Cross-origin resource sharing" |
| 351 | [csrf]: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet |
| 352 | "Cross-site request forgery" |
| 353 | [forbidden header name]: https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name |
| 354 | [releases]: https://github.com/github/fetch/releases |