Fetch and Working with APIs

Make HTTP requests from the browser with fetch, handle JSON, headers, errors, loading states and CORS.

Intermediate · about 5 hours · difficulty 2/5

Learn first: Asynchronous JavaScript: Callbacks, Promises and async/await, HTTP and HTTPS

fetch is the browser's built-in HTTP client and the foundation that data libraries wrap. Know it well before adopting abstractions.

The basics

const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }); then await res.json().

  • fetch only rejects on network failure. A 404 or 500 still resolves, so always check res.ok or res.status and throw your own error.
  • Read the body once, with the right method: json(), text(), blob(), formData().
  • Send files with FormData and let the browser set the multipart header.
  • credentials: "include" sends cookies to other origins (the server must allow it).

Building a small API layer

Wrap fetch in a helper that sets the base URL, adds auth headers, parses JSON, converts non-2xx responses into typed errors and supports AbortSignal. Every component then calls api.get("/jobs") instead of repeating boilerplate.

UI states

Every request has at least four states: idle, loading, success and error (plus empty). Design each one. Show skeletons instead of spinners for content, keep the previous data while refetching and let users retry errors.

CORS in one paragraph

Browsers block reading responses from a different origin unless the server sends Access-Control-Allow-Origin. Requests with custom headers or JSON bodies trigger an OPTIONS preflight. CORS is fixed on the server (or with a dev proxy), never by a frontend flag.

Move on when you have built a small API client with error handling and used it to power a page with all loading and error states.

Key concepts

  • fetch request options
  • Checking res.ok and status: fetch does not reject on 4xx/5xx
  • JSON, text, blob and FormData bodies
  • Headers and credentials
  • Loading, error and empty states
  • Reusable API client wrapper
  • CORS and preflight requests
  • Streaming responses

Mini project

Build a GitHub profile viewer that uses the public GitHub REST API through your own api helper, handles 404 and rate-limit errors, and shows skeleton loaders.

Check yourself

Your fetch call to an endpoint returning 500 went into the success branch. Why, and how do you fix it?

Free resources