Skip to content
GreenSnippets

fetch with a timeout and error handling

Abort slow HTTP requests with AbortSignal.timeout and turn non-2xx responses into real errors.

JavaScript
async function fetchJson(url, { timeoutMs = 8000, signal, ...init } = {}) {
  const signals = [AbortSignal.timeout(timeoutMs)];
  if (signal) signals.push(signal);

  const response = await fetch(url, { ...init, signal: AbortSignal.any(signals) });
  if (!response.ok) {
    const error = new Error(`HTTP ${response.status} for ${url}`);
    error.status = response.status;
    throw error;
  }
  return response.json();
}

How it works

fetch has no built-in timeout and only rejects on network failure, not on 404 or 500. This helper adds both: AbortSignal.timeout() cancels the request, and response.ok is checked so callers get an exception with the status code.

A caller-supplied signal is combined with the timeout using AbortSignal.any, so either can cancel the request.