fetch() in the browser hands you a Promise that resolves when the server responds, but it leaves the hard parts to you. fetch does not give a request a built-in timeout; Chrome gives fetch 300 seconds before it gives up on a dead connection, and Firefox gives it 90, both far longer than any user will wait. fetch does not retry a failed request. A response with an HTTP error status looks identical to one with a success status until you check response.ok. fetch does not add any caching beyond what the browser’s HTTP cache already does automatically.
You can fix all of this with a small wrapper around fetch. The patterns are: canceling requests with AbortController, setting your own deadlines, classifying failures so the UI can respond correctly, retrying only the requests that are safe to repeat, and deciding whether several requests run in parallel or one after another. By the end you will know how to build each piece and where each one breaks if you skip it.
Canceling requests with AbortController
fetch does not let you cancel a request by calling a method on the request itself. You cancel through AbortController, a browser API that pairs a controller with a signal. You pass the signal to fetch in the options object. When you call controller.abort(), the signal’s aborted property becomes true, an abort event fires on the signal, and every fetch using that signal rejects immediately with an error whose name is AbortError. AbortController shipped in 2017 and works in every modern browser except Internet Explorer.
const controller = new AbortController();
fetch('/api/items', { signal: controller.signal })
.then((response) => response.json())
.catch((err) => {
if (err.name === 'AbortError') {
// The request was canceled on purpose. Do not show an error.
} else {
// A real network failure. Surface it.
}
});
controller.abort();
Check err.name === 'AbortError' before you treat the rejection as a failure. A cancellation is intentional, and if your error handler reports it as a network error, users see failure messages for an action they triggered themselves.
AbortController has three constraints. First, once you abort a controller, its signal stays in the aborted state permanently. If you reuse that signal for a second request, the fetch rejects immediately with AbortError, so create a fresh controller for each operation. Second, if you pass the same signal to several fetch calls, one abort cancels all of them, which is the right tool when a page fires several related requests that should be torn down together. Third, aborting cancels the request only on the client. The server may still receive and process it, and the client will not receive the response, so aborting a write does not undo the change the server made.
Setting a timeout with AbortSignal
The default browser timeouts are far longer than a user will wait. Chrome waits 300 seconds before failing a connection; Firefox waits 90. A spinner that runs for minutes will lose the user.
Set your own deadline with AbortSignal.timeout, a static method that creates a signal which aborts itself after the number of milliseconds you pass:
fetch('/api/items', { signal: AbortSignal.timeout(10000) });
When that signal fires, the rejection has the name TimeoutError, not AbortError, so your handler can tell a deadline from a manual cancel. A practical range for most endpoints is 5 to 15 seconds, chosen per endpoint: a search autocomplete can fail fast, while a report generator needs longer. The same timeout strategy guidance applies: cancel the pending request the moment the deadline fires, rather than letting it linger.
To support both a manual cancel button and a timeout on the same request, use AbortSignal.any, which takes an array of signals and aborts when any one of them fires:
const controller = new AbortController();
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(10000)]);
fetch('/api/items', { signal });
Either the user clicking cancel or the deadline firing triggers the same abort path. AbortSignal.timeout and AbortSignal.any are newer than AbortController, so if your support matrix includes older browsers, build the timeout yourself with a controller and a setTimeout that calls abort.
Building a fetch wrapper that classifies errors
CORS (Cross-Origin Resource Sharing) is a browser security rule that blocks requests from other origins. fetch only rejects its promise for network-level failures: the connection dropped, DNS failed, or a CORS policy blocked the request. A 404 or 500 resolves normally, and response.ok is false. So the first rule is to check response.ok before you read the body.
A useful wrapper classifies every failure and returns one consistent shape to the caller. The categories are: network failure, timeout, HTTP error (4xx or 5xx), parse failure, and unknown. For each, the wrapper returns a success flag, the parsed data or an error payload, the HTTP status when there is one, and a hint about whether retrying is safe. That lets the UI branch on a small set of known cases instead of inspecting raw error objects. Handling Fetch Errors in Frontend Applications covers the UI side of this decision.
For the body, guard the JSON parse. A server that returns an HTML error page with a success status is a real situation; parsing its body as JSON throws, and an unguarded throw crashes the handler. Wrap the parse in a try/catch and return a parse error instead.
Keep the error messages meaningful. A 401 means the session expired, a 404 means the resource is gone, and a 500 means the server failed, so each deserves a different message and a different recovery path. Standardizing on a small set of error codes and logging them comprehensively makes a wrapper far easier to debug in production. If you work in TypeScript, building a typed wrapper around fetch removes a whole class of runtime errors.
Retrying idempotent requests with backoff
Some failures deserve a retry; others do not. A dropped connection or a temporary server overload can succeed on the second attempt. A 400 or 401 fails the same way every time, so retrying just adds load to a service that is already rejecting the request.
Retry only idempotent operations, meaning requests whose repeated execution leaves the server in the same state. GET is the obvious case. A POST that creates a resource is not: retrying it can create the resource twice, so a retry layer for writes needs an idempotency key or must not retry at all.
When you do retry, use exponential backoff: wait a short delay, double it after each attempt, and cap the number of attempts so the client gives up after a few tries. If the server sends a Retry-After header, respect its value instead of your own schedule. This matches the retry and backoff techniques that production services use. On top of retries, API error handling best practices include circuit breakers, which stop sending traffic to a failing service after a threshold of errors so failures do not cascade.
The timeout from the previous section pairs with this. Use a timeout in the 5 to 15 second range, cancel the pending request when it fires, then decide whether a retry applies. One slow endpoint should not consume a user’s session while the client waits.
HTTP caching and service workers
HTTP caching applies only to safe methods, which in practice means GET. A cached response has one of two states, fresh or stale, and the Cache-Control response header decides which. Cache-Control: private, max-age=60 keeps data fresh for 60 seconds, after which the browser treats it as stale.
Revalidation uses the ETag header, which holds a value representing the current state of the resource. On a reissued request, the browser adds If-None-Match with the previous ETag. If the data has not changed, the server responds with 304 Not Modified and an empty body, and the browser serves its cached copy.
Most of the time you do not write code for this; the browser does it. You reach for code when you need offline support or control over what gets cached. A service worker sits between the client and the server, intercepts fetch requests, and can serve from the CacheStorage API, support offline use, and update cached resources. That is the mechanism behind offline-first applications and the tool to use when the default HTTP cache is not enough.
Running requests in parallel or sequence
JavaScript runs one task at a time, so a fetch does not block other code; the browser handles the network in the background while your code continues. To run several independent requests at once, use Promise.all, which takes an array of promises and resolves when every one has resolved. This is the right tool for a dashboard that loads several sections that do not depend on each other. Fetch with Promise.all and async/await shows the pattern in action.
For dependent requests, run them sequentially with async/await inside a for...of loop. The await pauses the loop until the current request finishes, so each request starts only after the previous one completes. This also keeps you from hammering a server with a burst of requests when you only need the result of one to compute the next.
Promise.all resolves in the time of the slowest request, not the sum of all of them. If one request fails, Promise.all rejects with that error immediately, but the other requests keep running in the background unless you also abort them. Combine this with the AbortController pattern from earlier: give all the requests a shared signal so a failure or a user action can tear them down together. If you are working in React, fetching API data asynchronously adds lifecycle concerns around unmounting and cancellation.