JavaScript AbortController: Cancel Fetch Requests

Learn how AbortController and AbortSignal cancel fetch requests, handle AbortError, and clean up React effects and outdated searches.

JavaScript AbortController: Cancel Fetch Requests

What is AbortController, and When do you use it?

AbortController gives your code a way to signal that an asynchronous operation should stop. A common use is canceling a Fetch request when its result is no longer needed—for example, after a component unmounts or when a newer search replaces an older one.

An AbortController has a signal. Pass that signal to fetch(), then call controller.abort() when you want to cancel:

const controller = new AbortController();
const cancelButton = document.querySelector("#cancel");

fetch("/api/products", { signal: controller.signal })
  .then((response) => response.json())
  .then((products) => console.log(products))
  .catch((error) => {
    if (error.name === "AbortError") {
      console.log("The request was cancelled");
      return;
    }

    console.error("The request failed:", error);
  });

// Assume the page has a button with id="cancel".
cancelButton.addEventListener("click", () => controller.abort());

When a fetch is aborted, its Promise rejects with an AbortError. Aborting can also interrupt reading the response body. Handle cancellation separately from a genuine network or server error so it does not show as a failure to the user. MDN: Canceling a Fetch request · MDN: AbortSignal

Use it in a React effect

An effect can start a request when a component appears or when an input such as userId changes. Return a cleanup function that aborts the request when that effect is replaced or the component unmounts:

import { useEffect, useState } from "react";

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const controller = new AbortController();
    let ignore = false;

    async function loadUser() {
      try {
        setError(null);

        const response = await fetch(`/api/users/${userId}`, {
          signal: controller.signal,
        });

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

        const data = await response.json();
        if (!ignore) setUser(data);
      } catch (error) {
        if (error.name === "AbortError" || ignore) return;
        setError(error);
      }
    }

    loadUser();

    return () => {
      ignore = true;
      controller.abort();
    };
  }, [userId]);

  if (error) return <p>Could not load this profile.</p>;
  if (!user) return <p>Loading…</p>;
  return <h1>{user.name}</h1>;
}

When userId changes, React runs the previous effect's cleanup before starting the next effect. The old request is aborted, and unmounting also runs cleanup. React recommends that an effect fetching data either abort the request or ignore its result during cleanup. React: Synchronizing with Effects

Cancel an outdated search

The same effect cleanup works when a search term changes quickly. Each term starts a request; changing the term aborts the request for the previous term:

useEffect(() => {
  if (!query.trim()) {
    setResults([]);
    return;
  }

  const controller = new AbortController();
  let ignore = false;

  async function search() {
    try {
      const response = await fetch(
        `/api/search?q=${encodeURIComponent(query)}`,
        { signal: controller.signal },
      );

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

      const data = await response.json();
      if (!ignore) setResults(data);
    } catch (error) {
      if (error.name === "AbortError" || ignore) return;
      setError(error);
    }
  }

  search();
  return () => {
    ignore = true;
    controller.abort();
  };
}, [query]);

This cancels work that is still in flight and ignores a result if it has already completed just as the effect is cleaned up. Debouncing is a separate technique: it waits until input has paused before starting a request. Search interfaces often combine debouncing with aborting so they send fewer requests and cancel outdated work.

Important details

  • Create a new controller for each independent request or effect run. Once aborted, a signal stays aborted and cannot be reused for another fetch.
  • If the fetch has already resolved but the response body is still being read, aborting can still make body consumption reject.
  • Aborting the browser's fetch does not guarantee that a server which already received the request stops processing it. Treat cancellation as client-side control, not rollback for a server action.
  • Check response.ok separately. A 404 or 500 is an HTTP response, not an AbortError.

Try it yourself

Add a Cancel button to a page that fetches a large JSON resource. Keep the controller where the button handler can access it, pass its signal to fetch(), and call abort() when clicked. In the catch block, show a message for AbortError and a different message for other failures.

Recap

  • AbortController signals cancellation through its signal property.
  • Pass the signal in the Fetch options and call abort() to cancel the client request.
  • Handle AbortError as expected cancellation, separately from other errors.
  • React effect cleanup can abort requests when dependencies change or a component unmounts.
  • Aborting is not a guarantee that a server-side operation has been undone.

What's next?

Next, we’ll learn what debouncing is and where it helps, including search inputs.

Written by

Dev Likhon

Dev Likhon

Full Stack Developer & Tech Educator

6+ years of professional development experience.

About Me
Share:

Comments

Share what you learned or ask a question.

Loading comments...