Go to content
Web development

Canceling Fetch Requests with AbortController in TypeScript

When your TypeScript code calls fetch, the request keeps running until the server responds, even if the user has navigated away, typed a new search term, or the component that started the request has unmounted. Browsers and Node.js provide a built-in way to stop that work: the AbortController API. You create a controller, pass its signal to fetch, and call abort() when the result no longer matters. The pending promise rejects immediately with an error named AbortError. Your catch block can recognize that name and move on without treating the cancellation as a failure.

You’ll learn how to cancel a fetch when a React component unmounts, add a timeout, cancel several requests at once, and handle AbortError so intentional cancellations never appear in your error reporting. You’ll also see when cancellation is the right tool and when simply ignoring the stale response is good enough.

How AbortController cancels a fetch

An AbortController instance is a small object with two parts. The controller has an abort() method. Its signal property is an AbortSignal object, and you hand that signal to fetch through the signal option. When you call abort(), the signal fires, the browser aborts the request, and the fetch promise rejects with an AbortError.

const controller = new AbortController();

fetch('/api/data', { signal: controller.signal })
  .then((response) => response.json())
  .catch((error) => {
    if (error instanceof DOMException && error.name === 'AbortError') {
      return; // The request was canceled on purpose.
    }
    throw error;
  });

// Later, when the response no longer matters:
controller.abort();

In TypeScript, the catch variable is typed as unknown, so the example narrows it with instanceof DOMException before reading name. If your runtime lacks DOMException, check the name with a cast instead, for example (error as { name?: string }).name === 'AbortError'.

Two constraints apply to every pattern that follows.

First, a signal can only be used once. After you call abort(), the signal stays aborted permanently, and any fetch that receives it rejects immediately. For a retry or a new request, create a new controller.

Second, aborting is a client-side action. If the request already left the browser, the server may still receive and process it. AbortController stops your code from waiting and stops the browser from downloading the rest of the response; it does not rewind work that already happened on the server.

AbortSignal has been widely available in browsers since April 2018, including inside Web Workers, though Internet Explorer never supported it. Node.js 18+ includes AbortController natively; for earlier Node versions, use a polyfill.

Canceling a request when a component unmounts

In React, the natural home for a fetch is useEffect, because its cleanup function runs when the component unmounts or when the effect re-runs. Create the controller inside the effect, pass its signal to fetch, and call abort() in the cleanup function that useEffect returns.

import { useEffect, useState } from 'react';

type User = {
  id: string;
  name: string;
};

function UserProfile({ userId }: { userId: string }) {
  const [user, setUser] = useState<User | null>(null);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    const controller = new AbortController();

    async function loadUser() {
      try {
        const response = await fetch(`/api/users/${userId}`, {
          signal: controller.signal,
        });
        if (!response.ok) {
          throw new Error(`Request failed with status ${response.status}`);
        }
        const data = (await response.json()) as User;
        setUser(data);
      } catch (err) {
        if (err instanceof DOMException && err.name === 'AbortError') {
          return; // The component unmounted; nothing left to do.
        }
        setError(err instanceof Error ? err : new Error(String(err)));
      }
    }

    loadUser();

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

  return <div>{user ? user.name : error ? error.message : 'Loading...'}</div>;
}

One behavior surprises people new to this pattern: in development, React StrictMode mounts a component, unmounts it, and mounts it again, so the first fetch aborts immediately. StrictMode does this deliberately to verify that your cleanup is correct. The second mount runs the effect again with a fresh controller, and production builds skip the double cycle.

Note the dependency array. Because userId is a dependency, React tears down the previous effect, which aborts its fetch, before it runs the new one. Switching from one user to another cancels the stale request automatically.

Stopping state updates after a request is canceled

The AbortError check in the catch block prevents React from receiving a state update after unmount. When the cleanup calls abort(), the fetch promise rejects, the catch block sees AbortError, and the function returns before setUser or setError runs.

A common alternative is a boolean flag, often named cancelled or isMounted, that the code checks before updating state. The flag prevents the state write, but the network request keeps running: the browser holds the connection open and downloads the response you no longer want. AbortController does both jobs, because it actually cancels the request and saves bandwidth that the flag leaves in use.

The same reasoning applies outside React. If you start a fetch and later decide the result is irrelevant, calling abort() makes the promise reject so no later .then() runs with data nobody asked for. A guard variable can ignore the result, but it cannot stop the work.

Setting a timeout on a fetch

For requests that should not run forever, AbortSignal.timeout returns a signal that aborts itself after the deadline. Pass it straight to fetch:

try {
  const response = await fetch('/api/data', {
    signal: AbortSignal.timeout(5000),
  });
  const data = await response.json();
  return data;
} catch (error) {
  if (error instanceof DOMException && error.name === 'TimeoutError') {
    throw new Error('Request timed out');
  }
  throw error;
}

When the deadline fires, the promise rejects with a TimeoutError DOMException, a different name from AbortError, so your catch block can tell a timeout apart from a manual cancel.

The signal stays attached to the whole operation, not just the first await fetch(...). The fetch promise can resolve as soon as the response headers arrive, while response.json() still reads the body. The deadline covers that body-reading phase too, so a download that stalls mid-body still aborts.

One caveat: AbortSignal.timeout provides no way to cancel its own timer. If your code creates many of these signals with long deadlines, the timers linger after the requests finish. For that situation, build the timeout by hand with AbortController and setTimeout, and clear the timer in a finally block:

const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);

try {
  const response = await fetch('/api/data', { signal: controller.signal });
  return await response.json();
} finally {
  clearTimeout(timeoutId);
}

A plain abort() call rejects with AbortError rather than TimeoutError, because it carries no reason. If you want to keep the distinction, pass a reason to abort(), such as new DOMException('Timed out', 'TimeoutError'), and the rejection carries it.

Canceling several requests together

To cancel multiple fetches at once, pass the same signal to each fetch call. One abort() rejects all of them.

const controller = new AbortController();

async function loadDashboard() {
  try {
    const [usersResponse, postsResponse] = await Promise.all([
      fetch('/api/users', { signal: controller.signal }),
      fetch('/api/posts', { signal: controller.signal }),
    ]);
    // Render both sets of data.
  } catch (error) {
    if (error instanceof DOMException && error.name === 'AbortError') {
      return; // One abort canceled both requests.
    }
    throw error;
  }
}

// When the dashboard is no longer visible:
controller.abort();

Requests that should be cancelable independently get their own controllers; aborting one leaves the others running. Also note that Promise.all rejects on the first real error but does not cancel the other requests. If one endpoint fails and the rest no longer matter, call controller.abort() in the catch block so the survivors stop too.

To combine a manual cancel with a timeout, use AbortSignal.any, which returns one signal that aborts when any of its inputs abort. The combined signal does not tell you which input caused the abort, so if you need to respond differently to a timeout than to a user cancel, listen to the timeout signal directly and remove the listener in a finally block:

const controller = new AbortController();
const timeoutSignal = AbortSignal.timeout(5000);
const signal = AbortSignal.any([controller.signal, timeoutSignal]);

let timedOut = false;
const markTimedOut = () => {
  timedOut = true;
};
timeoutSignal.addEventListener('abort', markTimedOut);

try {
  const response = await fetch('/api/data', { signal });
  return await response.json();
} catch (error) {
  if (timedOut) {
    throw new Error('Request timed out');
  }
  if (error instanceof DOMException && error.name === 'AbortError') {
    return; // Canceled by the controller.
  }
  throw error;
} finally {
  timeoutSignal.removeEventListener('abort', markTimedOut);
}

AbortSignal.any arrived in Node.js later than AbortSignal.timeout, and both are newer than AbortController itself, so check support in the browsers and Node versions your app targets.

Distinguishing AbortError from real failures

In the catch block, check for AbortError first and return early, so an intentional cancel is not treated as a failure.

try {
  const response = await fetch('/api/data', { signal });
  if (!response.ok) {
    throw new Error(`Request failed with status ${response.status}`);
  }
  return await response.json();
} catch (error) {
  if (error instanceof DOMException && error.name === 'AbortError') {
    return; // Canceled on purpose; not a failure.
  }
  throw error; // A real error: report it and let the caller handle it.
}

Two details matter for this pattern.

HTTP status arrives separately from cancellation. A 404 or 503 resolves the fetch promise normally, so response.ok is false and your code should turn that status into a domain error before retrying or reporting. Cancellation and HTTP errors never arrive through the same channel.

Keep AbortError out of error tracking. When a user navigates away or a component unmounts, the abort is expected, not a bug, so it should not appear in your error counts.

Retries need the same separation. Because aborting does not undo server-side work, do not blindly retry a canceled write. If the request was a POST that creates a resource, the server may have already processed it. Use an idempotency key or an explicit server contract before retrying.

If your code runs several async steps after the fetch, call signal.throwIfAborted between steps. The method throws the signal’s abort reason if the signal has been aborted and does nothing otherwise, so a cancellation stops the remaining work at the next checkpoint instead of letting it run to completion.

When to cancel instead of ignoring the response

The clearest case for cancellation is a search box that fires a request on every keystroke. Responses arrive in the order the server finishes them, not the order you sent them, so an older response can land last and overwrite the newest results. For a search box, abort the previous request when a new one starts. The old promise rejects with AbortError, and its catch returns before touching state, so an outdated response cannot overwrite the latest one.

Cancellation also saves resources that ignoring cannot. The browser stops downloading the response body, which matters on a slow connection when a large payload is mid-transfer, and the server sees the connection close rather than continuing to send data.

Ignoring a stale response is acceptable when the request is cheap and fast and the only harm is a state write nobody sees. In that situation a guard flag works. But the flag pattern is fragile: the request still holds a connection open, and any code path that forgets the check writes stale data. AbortController uses roughly the same amount of code and removes the entire class of bug.

Keep the server-side caveat in mind. Aborting tells the browser to stop waiting, but the server may still receive and process the request. Cancellation protects your client and your bandwidth; it does not guarantee the server skipped the work, so design write endpoints to tolerate duplicate or orphaned requests.

More in Web development Back to top ↑