Skip to content

Guide · Open source

How to use fetch: a window.fetch polyfill tutorial

Updated · written with AI from the project's own documentation and checked against our catalogue data

fetch is a window.fetch polyfill: a JavaScript library that provides a Promise-based fetch() function for making web requests in browsers that do not support fetch natively. It is aimed at front-end developers who maintain web apps that must run on older browsers, or who want to replace XMLHttpRequest code with a simpler API. After this guide you will be able to install the package, import it, and send GET and POST requests with the patterns the README shows.

window.fetch polyfillJakeChampion/fetch · ★ 25.8k · MIT

Quick start

  1. 1Install the package. Run npm install whatwg-fetch --save in your project folder, as shown in the README.
  2. 2Import it in your app. Add import 'whatwg-fetch' near your entry file, or add it first in your webpack entry array.
  3. 3Make a request. Call fetch() with a URL, then read the body with response.json() or response.text().
  4. 4Check for errors. Add a catch handler, and check response.status yourself if you need non-2xx responses to reject.

Install the fetch polyfill with npm

The README installs the package with npm. Run the command below in your project folder. The README gives this package name for the install, even though the repository is named fetch.

Because the polyfill is meant to be bundled into browser code, it is a package-manager install that your build tool then includes.

npm install whatwg-fetch --save

Import the polyfill so window.fetch is available

Importing the package automatically polyfills window.fetch and related APIs. If you need the polyfill's own implementation, the package also exports it as fetch, so you can call native and polyfill versions side by side.

For webpack, the README says to add the package to the entry configuration before your application entry point.

  • Simple import: the polyfill is applied to window.fetch.
  • Named import: use the exported fetch as a polyfill-only function, which the README suggests for aborting requests in browsers with an outdated native fetch.
  • webpack: list 'whatwg-fetch' first in the entry array.
import 'whatwg-fetch' window.fetch(...)

Make GET requests for HTML and JSON

fetch() returns a Promise. Call response.text() to read HTML or response.json() to parse JSON. Add a catch handler so parsing or network failures do not go unnoticed.

The response also exposes headers.get(), status and statusText, which the README shows for reading response metadata.

fetch('/users.json') .then(function(response) { return response.json() }).then(function(json) { console.log('parsed json', json) }).catch(function(ex) { console.log('parsing failed', ex) })

Send form data and JSON with POST

To send a form, pass a FormData object as the body. To send JSON, set the Content-Type header to application/json and stringify the body. The README also shows a file upload that appends a file from an input element to a FormData object.

  • Form: body: new FormData(form)
  • JSON: headers with 'Content-Type': 'application/json' and body: JSON.stringify(...)
  • File: data.append('file', input.files[0]) and then send data as the body
fetch('/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Hubot', login: 'hubot', }) })

Handle HTTP error statuses correctly

The fetch Promise does not reject on HTTP error statuses such as 404 or 500. It only rejects on network failure or if something prevented the request from completing. To reject on any non-2xx status, the README suggests a custom check function that throws an error with the response attached.

  • Check response.status for a value from 200 to 299.
  • Throw an Error with response.statusText and attach the response to it.
  • Put the error handling in a catch at the end of the chain.

Understand cookies, CORS and other limitations

For cross-domain requests, CORS rules apply and are handled by the browser, which the polyfill cannot change. The README says cross-domain requests often need server-side headers. Always set credentials explicitly, such as 'same-origin' or 'include' for CORS, rather than relying on defaults, because older browsers used different defaults.

The README lists several limits: redirect and cache options are ignored or unsupported, keepalive is not supported, and the project does not work under Node.js. Review the Caveats section of the README before relying on any of these options.

  • Use credentials: 'include' for cross-domain requests that need cookies.
  • Set-Cookie headers cannot be read with response.headers.get(). Non-HTTP-only cookies are available through document.cookie.
  • Only the 'follow' redirect mode is available where the polyfill is active.
  • Aborting requests is documented in the README and supported by the polyfill.

What people use it for

  • Replacing XMLHttpRequest calls in a traditional web app with Promise-based code.
  • Loading HTML fragments into the page with fetch and response.text().
  • Posting a form or a file upload to a server endpoint with FormData.
  • Sending JSON payloads with a Content-Type header and JSON.stringify.

Frequently asked questions

Is fetch free to use?

The project is released under the MIT licence, according to the analysis for this page. Check the licence file in the repository for the full terms before you use it in a commercial project.

What do I need to install fetch?

The README uses npm, so you need npm to install the package. The README also recommends a separate Promise polyfill for older browsers that lack Promise support.

Do I need fetch polyfill in modern browsers?

No. The README says all modern browsers implement fetch natively, so no code from this project takes effect there. It is only needed for browsers that lack window.fetch.

Can I use fetch polyfill in Node.js?

No. The README says this project does not work under Node.js environments and is meant for web browsers only.

Why does my fetch request not fail on a 404 or 500 error?

The fetch Promise resolves on HTTP error statuses and only rejects on network failure or when the request cannot complete. Add a status check, as shown in the README, to throw an error for non-2xx responses.

What are alternatives to fetch polyfill?

The analysis lists axios, ky, got and node-fetch as comparable projects. This page does not compare their features in detail, so check each project's documentation for your needs.

New agent skills, repos and AI tools — every week

The best new skills and open-source projects, the fastest-growing repos, and one free prompt. Five minutes to read. Unsubscribe anytime.

Our verdict

Use fetch if you maintain a browser app that must still support older browsers and you want window.fetch available after importing a package. Pick a different option if you only target modern browsers, because native fetch already exists there, or if you need Node.js support, redirect modes, cache options or keepalive, which the README says are unsupported or ignored.

Install options & downloads