Skip to content

Fetch API

Use the Fetch API to make HTTP requests, handle responses, and work with async/await.

What you'll learn

  • How fetch() makes HTTP requests and returns promises
  • Using async/await to write clean asynchronous code
  • Handling errors: network failures vs. HTTP error status codes
  • Sending different content types: JSON, form data, and headers

Concept

Fetch API

The Fetch API is the modern, built-in way to make HTTP requests from JavaScript. It replaces the old XMLHttpRequest with a cleaner, promise-based interface. Whenever your web page needs to load data from a server — fetching a user profile, submitting a form, loading search results — fetch() is the tool. It is supported in all modern browsers and needs no library.

The Basics

fetch(url) makes a GET request and returns a Promise that resolves to a Response object:

const response = await fetch("https://api.example.com/users");
const data = await response.json();

The response is a stream — you must call .json(), .text(), or .blob() to read the body. This two-step process (fetch, then parse) is because the headers are available immediately, but the body may still be downloading.

async/await

async/await makes asynchronous code read like synchronous code. Mark a function async, then await promises inside it. No more nested .then() callbacks:

async function getUser(id) {
  const response = await fetch(`/api/users/${id}`);
  return response.json();
}

If a promise rejects (an error), await throws — so wrap your code in try/catch to handle failures gracefully.

Error Handling

fetch only rejects on network failure — a DNS error, a dropped connection, a CORS block. It does not reject on HTTP error status codes (404, 500). A 404 response is a successful fetch that happens to contain an error. You must check response.ok (true for 2xx status codes) or response.status yourself:

if (!response.ok) {
  throw new Error(`HTTP ${response.status}`);
}

Forgetting this is the most common fetch bug — your code silently treats an error response as success.

Sending Data

To send data (POST, PUT, etc.), pass a second argument with options:

fetch(url, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Ada" })
});

The body must be a string. For JSON, set the Content-Type header and stringify the body. For file uploads, use FormData instead of JSON.

Example

              // A complete data-fetching function with error handling
async function fetchUsers(page = 1) {
  try {
    const response = await fetch(`https://api.example.com/users?page=${page}`, {
      headers: { "Accept": "application/json" }
    });

    // fetch does NOT throw on 404/500 — check manually
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const data = await response.json();
    return data.users;
  } catch (error) {
    // Network failure OR our thrown error lands here
    console.error("Failed to fetch users:", error.message);
    return [];  // return a safe fallback
  }
}

// POST with a JSON body
async function createUser(userData) {
  const response = await fetch("https://api.example.com/users", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${getToken()}`
    },
    body: JSON.stringify(userData)
  });

  if (!response.ok) throw new Error("Create failed");
  return response.json();
}
            

fetchUsers handles both network errors (caught by try/catch) and HTTP errors (checked via response.ok). It returns a safe fallback on failure. createUser sends a POST with JSON body and an auth header. The two-step pattern — fetch, then check ok, then parse — is the correct way to use fetch.

Try it

  • JSON Formatter

    API responses are JSON — format and inspect what your fetch calls return.

  • JWT Decoder

    Fetch calls often send JWT tokens in the Authorization header — decode one to inspect.

Common mistakes

The mistake

Assuming fetch throws on a 404 or 500 response.

The fix

fetch only rejects on network failure. HTTP error responses (4xx, 5xx) still resolve successfully. Always check response.ok or response.status and throw manually to handle HTTP errors.

The mistake

Forgetting to set Content-Type: application/json when sending a JSON body.

The fix

If you send JSON.stringify(data) as the body, you must set headers: { 'Content-Type': 'application/json' }. Without it, the server does not know to parse the body as JSON and may reject the request.

Related Cheatsheets

Practice Fetch API

7 exercises

Practice Fetch API

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors