How to cancel a fetch request in JavaScript

Canceling fetch requests is crucial for preventing unnecessary network usage, avoiding race conditions, and improving application performance when requests become obsolete. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented request cancellation in search interfaces, navigation handlers, and component cleanup routines. From my expertise, the most effective approach is using the AbortController API which provides standardized request cancellation for fetch operations. This technique prevents memory leaks and ensures only relevant requests complete execution.

Use AbortController to create an abort signal and cancel fetch requests when needed.

const controller = new AbortController()
const signal = controller.signal

fetch('/api/data', { signal })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('Request was cancelled')
    }
  })

controller.abort()

Here new AbortController() creates a controller instance, and controller.signal generates the abort signal passed to the fetch options. When controller.abort() is called, the fetch request is immediately cancelled and throws an ‘AbortError’. The catch block checks for this specific error type to handle cancellation appropriately. This pattern is essential for component unmounting, route changes, or when newer requests supersede older ones.

Best Practice Note:

This is the same approach we use in CoreUI components for search input debouncing and navigation-based request cleanup. Always clean up pending requests in useEffect cleanup functions or component unmount handlers to prevent memory leaks and unwanted state updates.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author