What happens when you abort an API request?
When you abort an API request, you're essentially canceling the request before it completes, typically to avoid unnecessary work or prevent side effects (like setting state on an unmounted component in React).
In modern JavaScript, especially with the Fetch API, this is commonly done using an AbortController
.
π How it works under the hood:
- AbortController creates a signal (
AbortSignal
) that is passed to the fetch request. - If you call
abort()
on the controller:- The fetch is terminated immediately.
- The
Promise
returned byfetch()
is rejected with an error of typeDOMException
and the message"AbortError"
.
const controller = new AbortController(); fetch('/api/data', { signal: controller.signal }) .then(response => response.json()) .catch(error => { if (error.name === 'AbortError') { console.log('Request was aborted'); } else { console.error('Other error:', error); } }); controller.abort(); // Aborts the request
π Browser Behavior:
- The browser stops downloading the response body, freeing up memory and bandwidth.
- The server might still process the request unless it supports abort/cancel from the client side (most don't).
- If the request already completed before the abort, the
abort()
call has no effect.
β Real-life Use Cases:
-
Component Unmounting in React:
- Prevents setting state after a component unmounts, avoiding memory leaks and warnings.
-
Search Input / Autocomplete:
- Abort previous requests as the user types, so only the latest result is shown.
-
Timeouts / Performance Optimization:
- Abort slow requests after a certain duration to keep the app responsive.
π What Doesnβt Happen:
- No rollback or undo on the server β if the server has already processed the request, it won't know that the client aborted it.
- In older APIs like
XMLHttpRequest
, aborting was also possible, but Fetch'sAbortController
is the modern and cleaner way.
π§ Pro Tip:
If you're using tools like Axios, it also supports request cancellation via AbortController
(in newer versions), or with a CancelToken
in older versions.