What is fetch?

Fetch is a built‑in web API that lets you make network requests (like getting data from a server) directly from JavaScript. Think of it as a modern replacement for older tools such as XMLHttpRequest. You call fetch with a URL, and it returns a Promise that eventually gives you the response.

Let's break it down

  • fetch(url, options?) - the first argument is the address you want to talk to. The optional second argument lets you set the HTTP method (GET, POST, etc.), headers, body data, and other settings.
  • Promise - fetch doesn’t block the page. It immediately returns a Promise, which you handle with .then() or await.
  • Response object - when the Promise resolves, you get a Response object. You can read its status (200, 404, …) and extract the body as text, JSON, Blob, etc., using methods like response.json() or response.text().
  • Error handling - network failures reject the Promise, while HTTP errors (like 404) still resolve; you need to check response.ok yourself.

Why does it matter?

Fetch makes it easy to talk to APIs, load extra data, or submit forms without reloading the page. Because it uses Promises, the code is cleaner and more readable than the callback‑heavy XMLHttpRequest. It also works in all modern browsers and follows the same standards used by the rest of the web (e.g., CORS, streaming).

Where is it used?

  • Loading JSON data for single‑page applications (React, Vue, Angular).
  • Submitting form data via AJAX.
  • Downloading images, videos, or other files on the fly.
  • Interacting with third‑party APIs (weather, maps, payment gateways).
  • Service workers use fetch to intercept and cache network requests.

Good things about it

  • Simple syntax - one line to start a request.
  • Promise‑based - works naturally with async/await.
  • Flexible - supports all HTTP methods, custom headers, and request bodies.
  • Built‑in - no extra libraries needed in modern browsers.
  • Streaming support - you can read large responses piece by piece.

Not-so-good things

  • Not supported in very old browsers (IE 11 needs a polyfill).
  • Errors for HTTP status codes must be handled manually; fetch only rejects on network failures.
  • CORS restrictions can block requests to other domains unless the server allows them.
  • Complex multipart/form‑data handling can be a bit verbose compared to helper libraries.