Skip to content
← cd ../posts
[Developer Tools]5 min read

Fetch Timeouts: Cancel Slow Requests and Response Bodies

Use AbortSignal to bound fetch and body reads, preserve caller cancellation, and test timeout behavior with a working local HTTP server.

An emerald timing dial controls a flowing stream of response cards through a gate, with an amber stalled card at the boundary.

Quick answer

Pass an AbortSignal to fetch and keep the timeout policy active while consuming the response body. Combine the timeout with the caller's cancellation signal, so navigation or a cancelled job can stop the same operation. A timer that only rejects a competing promise stops your wait; it does not, by itself, tell fetch to cancel its work.

A shipping dashboard calls a quote API. The server sends HTTP 200 quickly, then stalls halfway through its JSON body. A timeout cleared immediately after await fetch(url) leaves await response.json() waiting. The customer still sees a spinner even though the application appears to have a timeout. The boundary needs to include the body read.

Separate response headers from a usable result

Fetch resolves to a Response once the response status and headers are available. Reading the body is another asynchronous operation. Fetch also does not reject just because the server returns an HTTP error status; check response.ok before treating a response as successful. MDN's Fetch guide explains both behaviors and how cancellation affects body consumption.

Decide what your helper promises to return. A helper returning parsed JSON can own the request and body-read policy together. A helper returning a streaming Response needs a documented lifetime for its cancellation signal; its caller still has work to do. Clearing a timer at the headers boundary is appropriate only when a headers-only timeout is actually your intended policy.

Run a local timeout laboratory

Save this as fetch-timeout-lab.mjs and run node fetch-timeout-lab.mjs using Node.js 22 or later. The example uses built-in modules, binds an automatically chosen port on 127.0.0.1, and makes no requests to an external service. It was verified with Node.js 22.17.1. Node's global API documentation covers fetch, AbortSignal.timeout, and AbortSignal.any.

javascript
import assert from 'node:assert/strict';
import { once } from 'node:events';
import { createServer } from 'node:http';
import { setTimeout as delay } from 'node:timers/promises';

async function fetchJSON(url, { timeoutMs = 1000, signal } = {}) {
  if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 60000) {
    throw new RangeError('timeoutMs must be an integer from 1 to 60000');
  }
  const timeout = AbortSignal.timeout(timeoutMs);
  const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
  try {
    const response = await fetch(url, { signal: combined });
    if (!response.ok) {
      await response.body?.cancel();
      throw new Error(`HTTP ${response.status}`);
    }
    // Await the body inside the same error and cancellation boundary.
    return await response.json();
  } catch (error) {
    // A body-read rejection can have a different name from the signal reason.
    // This helper consistently surfaces the reason of the winning signal.
    if (combined.aborted) throw combined.reason;
    throw error;
  }
}

const server = createServer((request, response) => {
  if (request.url === '/slow-body') {
    response.writeHead(200, { 'Content-Type': 'application/json' });
    response.flushHeaders();
    response.write('{"ok":'); // Deliberately never finishes the JSON body.
    response.on('close', () => server.emit('slowClosed'));
    return;
  }
  if (request.url === '/unavailable') {
    response.writeHead(503).end('Try later');
    return;
  }
  response.setHeader('Content-Type', 'application/json');
  response.end(request.url === '/invalid-json' ? '{' : '{"ok":true}');
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const origin = `http://127.0.0.1:${server.address().port}`;

try {
  assert.deepEqual(await fetchJSON(origin), { ok: true });
  await assert.rejects(fetchJSON(origin + '/unavailable'), /HTTP 503/);
  await assert.rejects(fetchJSON(origin + '/invalid-json'), SyntaxError);
  await assert.rejects(fetchJSON(origin, { timeoutMs: 0 }), RangeError);

  const disconnected = once(server, 'slowClosed');
  await assert.rejects(
    fetchJSON(origin + '/slow-body', { timeoutMs: 500 }),
    (error) => error.name === 'TimeoutError',
  );
  // Verify that the unfinished response was closed, not left running.
  await Promise.race([
    disconnected,
    delay(5000, undefined, { ref: false }).then(() => {
      throw new Error('Server did not observe the closed response');
    }),
  ]);

  const caller = new AbortController();
  const reason = new Error('Screen closed');
  caller.abort(reason);
  await assert.rejects(
    fetchJSON(origin, { signal: caller.signal }),
    (error) => error === reason,
  );
  console.log('Success, HTTP error, and invalid JSON checks passed.');
  console.log('Slow body timed out; server observed response closure.');
  console.log('Caller cancellation and timeout validation checks passed.');
} finally {
  server.closeAllConnections();
  await new Promise((resolve, reject) => {
    server.close((error) => error ? reject(error) : resolve());
  });
}

Expect three lines reporting successful HTTP/JSON checks, closure of the timed-out response, and successful caller-cancellation checks. The fixture sends an incomplete JSON document and deliberately never calls end for that response. Its close event proves that the client did more than stop awaiting a result: the server observed the unfinished response close.

The test uses a 500 ms operation timeout to remain quick. That is a fixture value, not a recommendation for your quote provider. It does not assert an exact elapsed duration. The separate five-second guard detects a missing close event, and finally closes the local server's connections. On a heavily overloaded machine, allow enough time for the request to reach the fixture before expecting that close event.

Combine cancellation reasons deliberately

AbortSignal.any creates a signal that aborts when one of its input signals aborts, preserving the triggering reason. It also handles an already-aborted input. That lets a screen-level AbortController and a request timeout participate in one cancellation policy without overwriting each other.

The final assertion passes an already-cancelled caller signal and checks the identity of its Error object. In a UI, keep a controller for the operation and call abort when the user dismisses that operation. In a job worker, connect cancellation to the job's lifecycle. Create a fresh timeout signal for each new attempt; an aborted signal cannot be reset and reused.

Our helper catches errors from both fetch and response.json. If the combined signal has aborted, it exposes that signal's reason consistently. This is an explicit classification policy: a timeout reason becomes TimeoutError, while the supplied caller Error stays the same object. Without normalization, a body-read rejection may have a different error name. If cancellation and another failure happen nearly together, this helper gives the aborted signal precedence; document that choice in an application where precise error attribution matters.

Keep HTTP, parsing, and cancellation failures distinct

The 503 fixture exercises a completed HTTP response. The malformed JSON fixture exercises a successful HTTP status with an unusable body. Neither should be reported as a timeout. In the helper, those failures keep their own errors unless cancellation has already won. A production API client may expose structured error classes with a status, endpoint label, and retry classification instead of the demonstration's plain HTTP Error.

Cancel an error response body if you will not consume it. If you need an error payload for diagnostics, read it under a deliberate byte limit and timeout policy rather than retaining an arbitrarily large body. Avoid putting authorization headers, private query parameters, or full customer payloads into timeout logs. The HTTP status explorer helps interpret status codes; it cannot tell you whether an individual request timed out before or after headers.

Choose a budget for the whole operation

The helper starts its timeout when it is called. Time spent waiting in an application queue before that call is outside its budget. If a screen has a total latency budget, track that at the caller and propagate cancellation into queued and active work. A per-request timeout alone does not bound a batch containing many sequential attempts.

For concurrent calls, keep timeout handling inside the task whose completion releases a worker slot. The bounded API concurrency guide demonstrates why a pool needs the returned promise to cover the complete task. Releasing a slot after headers while body processing continues defeats that resource boundary.

Aborting a client request does not roll back a remote business action. The server may already have accepted or completed a write. If you later adapt this GET helper to payments, bookings, or other mutations, treat a timeout as an uncertain result and apply the retry and idempotency checklist. Keep retry count, backoff, and the overall operation deadline explicit. Repeatedly granting a full new timeout can turn a short intended wait into a much longer one.

Understand what this timeout cannot guarantee

Cancellation is cooperative. It cannot interrupt arbitrary synchronous JavaScript, and a blocked event loop can delay timeout handling. A large JSON parse or CPU-heavy transformation needs its own design for size limits and scheduling. A network timeout is also not a response-size limit: a fast server can send more bytes than your application should hold in memory.

In browsers, AbortSignal.timeout is specified in terms of active time and can pause with a suspended context. Do not describe it as a universal wall-clock deadline. Check support for the browser versions you ship. That API also has no method for cancelling its own timer; if you require explicit timer disposal, use a controller with a timer you can clear in finally, after the body operation settles.

This example covers a small JSON GET client. It does not implement streaming progress, a maximum payload size, schema validation, redirects policy, retries, or cancellation of work inside another service. Add the controls your endpoint requires, and test their interaction with the same slow-body fixture.

A timeout checklist before shipping

  • State whether the budget covers queueing, headers, the body, and downstream processing.
  • Pass cancellation to fetch rather than only rejecting a competing promise.
  • Await body consumption inside the helper's cancellation and error boundary.
  • Preserve caller cancellation when adding a timeout signal.
  • Distinguish HTTP errors, malformed payloads, timeouts, and user cancellation.
  • Test a server that sends headers promptly and then never finishes its body.
  • Verify that cancellation closes the unfinished response in your runtime.
  • Bound retry attempts, response size, and total operation time separately.

A useful timeout test makes the network operation stop and observes the outcome. A promise rejecting on schedule is only one part of that contract.

Related Posts

Useful Tools For This Topic

explore_all →