Coordinate asynchronous work

Cancel a Browser Fetch Request and Handle AbortError

Learn how to cancel browser fetch with AbortController, handle AbortError during fetch or JSON reading, and start another request safely.

Editorial illustration for Cancel a Browser Fetch Request and Handle AbortError

To cancel a pending browser fetch(), create an AbortController, pass its signal in the fetch options, and call abort() when the user selects Cancel. Catch AbortError around both fetch() and the response-body read. That way, an intentional cancellation does not appear to be an ordinary request failure, while other errors still get reported.

Pass an AbortSignal to fetch and request cancellation

The controller and request need to be connected explicitly. new AbortController() gives you a controller; controller.signal is the signal to pass to fetch(). Creating the controller alone does not cancel an arbitrary promise. The operation has to use the signal, as fetch() does when it receives one in its options. Calling controller.abort() then requests cancellation of the associated fetch. See the AbortController documentation for the controller’s role.

This example is for a modern browser page after its body exists. Run it from that page’s JavaScript or developer console. /api/data must be an existing endpoint that returns JSON. The supplied Web API sources do not establish Node.js-specific behavior.

const startButton = document.createElement("button");
startButton.textContent = "Start request";

const cancelButton = document.createElement("button");
cancelButton.textContent = "Cancel";
cancelButton.disabled = true;

const status = document.createElement("pre");
status.textContent = "Ready.";
document.body.append(startButton, cancelButton, status);

let currentController = null;

async function startRequest() {
  const controller = new AbortController();
  currentController = controller;
  startButton.disabled = true;
  cancelButton.disabled = false;
  status.textContent = "Loading...";

  try {
    const response = await fetch("/api/data", {
      signal: controller.signal
    });
    const data = await response.json();
    status.textContent = JSON.stringify(data);
  } catch (error) {
    if (error?.name === "AbortError") {
      status.textContent = "Cancelled.";
    } else {
      status.textContent = "Request failed. See console.";
      console.error(error);
    }
  } finally {
    currentController = null;
    startButton.disabled = false;
    cancelButton.disabled = true;
  }
}

startButton.addEventListener("click", startRequest);
cancelButton.addEventListener("click", () => {
  if (currentController !== null) {
    currentController.abort();
  }
});

Start a request, then select Cancel while it is still pending. The expected outcome is Cancelled., not the ordinary failure message. If the request finishes first, cancellation cannot retroactively change the displayed result. The disabled buttons make the example’s controls reflect whether there is an active request.

Handle AbortError from fetch or response-body reading

There are two places to wait in this example: await fetch(...) and await response.json(). According to MDN’s AbortSignal documentation, calling abort() makes a pending fetch promise reject with a DOMException named AbortError. Even if fetch() has already fulfilled, aborting before the response body has been read can make that body read reject with AbortError. Keeping both awaits in one try block covers either point of cancellation.

The example calls abort() without a custom reason and checks the caught error’s name. Its AbortError branch treats cancellation as a deliberate outcome. The other branch reports the error to the console rather than silently treating every rejection as a cancelled request. This distinction matters when the endpoint fails to provide usable JSON: selecting Cancel and encountering an unrelated error should not produce the same message.

Cancellation is tied to work that uses the signal, not to every promise in the surrounding function. If you add another asynchronous operation, merely creating this controller does not make that operation cancellable. Decide separately whether that operation accepts a signal and what its cancellation should mean.

Use a fresh controller for the next request

After an abort, do not pass the old signal to another fetch. An aborted signal cannot be reset: MDN notes that a fetch given the same aborted signal rejects immediately. That would make a second click look like an instant cancellation instead of a new request.

The example creates its controller inside startRequest(), so every click that starts a request gets a new signal. It clears currentController when the attempt finishes, leaving the Cancel button with no completed request to target. For a quick check, cancel one pending attempt and then select Start request again. The second attempt should enter Loading... with its own controller; whether it eventually displays JSON depends on the endpoint returning a response that can be read as JSON.

Find a note

Search by topic, title, or keyword.