The Fetch API

Topic 5 of 5 in Asynchronous code7 min readBeginnerFree course

Overview

fetch requests a URL and gives you back a promise for the response. It’s how web pages talk to servers: loading data, saving changes, searching, uploading files.

JavaScript
const response = await fetch('/api/courses');
const courses = await response.json();

Reading the body is a second step: response.json(), response.text() and response.blob() all return promises too. That’s because the response headers arrive first, and the body may still be downloading.

fetch(‘/api/courses’) sends an HTTP GET request to the server, which sends back a response with a status, headers and a body. The Response object arrives first; check if (!res.ok) and throw; then await res.json() to read the body. fetch resolves for any reply, including 404 and 500, and rejects only when no reply arrives: offline, DNS failure, CORS block or abort.

Requests and responses

Every HTTP exchange has two halves.

The request says what you want:

  • a URL — /api/courses/42
  • a method — GET to read, POST to create, PUT/PATCH to update, DELETE to remove
  • headers — extra information, such as the type of data being sent
  • an optional body — the data you’re sending

The response says what happened:

  • a status code — 200 OK, 201 Created, 404 Not Found, 500 Server Error
  • headers — such as Content-Type: application/json
  • a body — the data itself
JavaScript
const res = await fetch('/api/courses');
res.status;                       // 200
res.ok;                           // true for any status 200–299
res.headers.get('Content-Type');  // 'application/json; charset=utf-8'

Checking for errors

A 404 or 500 response is still a successful fetch — the server answered. Check ok yourself:

JavaScript
const response = await fetch('/api/courses/42');
if (!response.ok) {
  throw new Error(`Server replied ${response.status}`);
}

fetch itself only rejects when the request couldn’t be made at all, for example when the user is offline.

A full, careful request handles both kinds of failure:

JavaScript
async function getJson(url) {
  let res;
  try {
    res = await fetch(url);
  } catch (error) {
    throw new Error('Network problem — are you online?', { cause: error });
  }
  if (!res.ok) {
    throw new Error(`Server error ${res.status} for ${url}`);
  }
  return res.json();
}

Wrap it once like this and reuse it everywhere, instead of repeating the checks.

Query strings

To send parameters in a GET request, build the URL with URLSearchParams, which encodes spaces and special characters correctly:

JavaScript
const params = new URLSearchParams({ q: 'arrow functions', level: 'Beginner' });
const res = await fetch(`/api/search?${params}`);
// /api/search?q=arrow+functions&level=Beginner

Gluing user input straight into a URL ('/api/search?q=' + input) breaks as soon as someone types & or #.

Sending data

JavaScript
await fetch('/api/progress', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ topic: 'fetch-api', done: true }),
});

The Content-Type header tells the server the body is JSON. Forgetting JSON.stringify is a common mistake — the body would be sent as the useless text [object Object].

Sending form data and files

For HTML forms and file uploads, pass a FormData object as the body. The browser sets the right headers for you:

JavaScript
const form = document.querySelector('#profile');
await fetch('/api/profile', {
  method: 'POST',
  body: new FormData(form), // includes any <input type="file"> too
});

Authentication headers

APIs often need a token in a header:

JavaScript
await fetch('/api/me', {
  headers: { Authorization: `Bearer ${token}` },
});

Never put secret API keys in browser JavaScript — anyone can read them. Secrets belong on your server.

Cancelling a request

JavaScript
const controller = new AbortController();
fetch('/api/search?q=loops', { signal: controller.signal });
controller.abort(); // e.g. when the user types again

An aborted fetch rejects with an AbortError, which you usually ignore. You can also give a request a time limit:

JavaScript
const res = await fetch(url, { signal: AbortSignal.timeout(5000) }); // give up after 5 s

Showing loading and error states

Real interfaces show the user what’s happening:

JavaScript
async function showCourses() {
  list.textContent = 'Loading…';
  try {
    const courses = await getJson('/api/courses');
    list.innerHTML = courses.map((c) => `<li>${c.title}</li>`).join('');
  } catch (error) {
    list.textContent = 'Could not load courses. Please try again.';
    console.error(error);
  }
}

(In real code, prefer creating elements over innerHTML for data from a server — see Creating elements.)

CORS

CORS errors mean the server didn’t allow requests from your page’s origin. That has to be fixed on the server, not in your fetch call.

Browsers only let a page read responses from its own origin (same protocol, domain and port) unless the other server says otherwise with Access-Control-Allow-… headers. This protects users: a random website can’t quietly read your bank’s API using your logged-in session. If you control the API, add the right headers there; if you don’t, call it from your own server instead.

You can debug any of these issues in the Network panel of DevTools, which shows every request, its status, headers and body.

Exercise

Load a list of courses

Write loadCourses() that fetches /api/courses, throws if the response isn’t OK, and returns the parsed JSON. Then write saveProgress(topic) that POSTs { topic, done: true } as JSON to /api/progress.

JavaScript
async function loadCourses() {
  // your code here
}

async function saveProgress(topic) {
  // your code here
}

Summary

  • fetch returns a promise for a Response; reading the body is a second promise.
  • It only rejects on network failure — check response.ok for HTTP errors.
  • Send JSON with method, headers and a stringified body.
  • Build query strings with URLSearchParams so values are encoded safely.
  • Cancel requests with AbortController; CORS errors must be fixed on the server.