JavaScript Fetch API Guide: Handle Errors, Timeouts, JSON Responses, and Retries
javascriptfetch-apiapisweb-developmentdebugging

JavaScript Fetch API Guide: Handle Errors, Timeouts, JSON Responses, and Retries

TThe Code Website Editorial Team
2026-12-02
7 min read

Use reliable Fetch API patterns for HTTP errors, safe JSON parsing, timeouts, cancellation, and carefully controlled retries.

Fetch is straightforward until a request times out, returns a non-2xx status, or contains a response that is not valid JSON. This guide provides reusable JavaScript fetch patterns for GET and POST requests, HTTP error handling, safe response parsing, abort-based timeouts, cancellation, and carefully limited retries.

Overview

The Fetch API returns a promise for a Response object. A common mistake is to treat every failed HTTP request as a rejected promise. In practice, fetch() generally rejects when the request cannot be completed, such as when the browser reports a network failure or an attached abort signal cancels the operation. A server response with a status such as 400, 401, 404, or 500 still produces a response object, so your code must check response.ok or response.status explicitly.

A reliable JavaScript API request usually has five steps:

  1. Create the request with the correct URL, method, headers, and body.
  2. Set a clear cancellation or timeout policy.
  3. Distinguish network and abort errors from HTTP errors.
  4. Parse the response according to its actual content type.
  5. Retry only operations and failures that are safe to retry.

Keep transport concerns separate from application concerns. A fetch helper can normalize HTTP and parsing errors, while the calling code decides whether to show a message, refresh authentication, preserve form data, or try again.

Checklist by scenario

Basic GET request with HTTP error handling

Start by checking the response before parsing its body. This prevents a successful JSON parse from hiding a server-side error.

async function getUser(userId) {
  const response = await fetch(`/api/users/${encodeURIComponent(userId)}`, {
    headers: {
      Accept: "application/json"
    }
  });

  if (!response.ok) {
    throw new Error(`Request failed with HTTP ${response.status}`);
  }

  return response.json();
}

getUser("42")
  .then((user) => console.log(user))
  .catch((error) => console.error("Could not load user:", error));

Use encodeURIComponent() for a value inserted into a URL path or query component. For more complex query strings, URLSearchParams is easier to maintain than manual concatenation.

POST JSON data

When sending JSON, serialize the payload and declare the media type. The server may require additional authentication or anti-forgery headers, so match the endpoint contract rather than assuming every API uses the same scheme.

async function createTask(task) {
  const response = await fetch("/api/tasks", {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify(task)
  });

  if (!response.ok) {
    const message = await readErrorMessage(response);
    throw new Error(`Could not create task (${response.status}): ${message}`);
  }

  return response.json();
}

async function readErrorMessage(response) {
  const contentType = response.headers.get("content-type") || "";

  if (contentType.includes("application/json")) {
    const data = await response.json().catch(() => null);
    return data?.message || "The server returned an error.";
  }

  const text = await response.text().catch(() => "");
  return text || "The server returned an error.";
}

A response body is a stream and should not normally be consumed twice. Decide whether the error path needs JSON or text, then read it once.

Safe JSON parsing

Do not assume every successful response contains JSON. A 204 No Content response, a plain-text health check, or an upstream proxy error page can make response.json() fail. A small helper can inspect the content type and tolerate an empty body.

async function readJsonIfPresent(response) {
  if (response.status === 204) return null;

  const contentType = response.headers.get("content-type") || "";
  if (!contentType.includes("application/json")) {
    throw new Error("Expected a JSON response.");
  }

  return response.json();
}

Content-type checks are a useful guard, not a substitute for validating the returned data. If the application depends on fields such as id or items, validate their shape before using them. A JSON formatter or validator can help inspect unfamiliar payloads; see the JSON Formatter and Validator Guide.

Fetch timeout with AbortController

Fetch does not automatically impose the application timeout your interface needs. Use an AbortController and clear the timer when the request finishes.

async function fetchWithTimeout(url, options = {}, timeoutMs = 8000) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeoutMs);

  try {
    return await fetch(url, {
      ...options,
      signal: controller.signal
    });
  } finally {
    clearTimeout(timer);
  }
}

try {
  const response = await fetchWithTimeout("/api/report", {}, 8000);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
} catch (error) {
  if (error.name === "AbortError") {
    console.error("The request timed out or was cancelled.");
  } else {
    console.error("The request could not be completed.", error);
  }
}

There is an important distinction between a timeout controller created by a helper and a user-controlled signal. In a search box or route transition, the caller may need to cancel the request for its own reason. A production helper can accept an external signal and combine it with a timeout, but it should document which cancellation reason the caller receives.

Retry transient failures carefully

Retries are appropriate only when the operation is safe to repeat or the API supports idempotency. Retrying a read-only GET after a temporary network failure is different from blindly repeating a payment, order, or account-creation request. For POST requests, follow the API's idempotency mechanism if one exists.

function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

function isRetryableStatus(status) {
  return status === 408 || status === 425 || status === 429 || status >= 500;
}

async function fetchWithRetry(url, options = {}, settings = {}) {
  const {
    attempts = 3,
    baseDelayMs = 300,
    signal
  } = settings;

  for (let attempt = 0; attempt < attempts; attempt += 1) {
    try {
      const response = await fetch(url, { ...options, signal });

      if (response.ok || !isRetryableStatus(response.status) || attempt === attempts - 1) {
        return response;
      }
    } catch (error) {
      if (error.name === "AbortError" || attempt === attempts - 1) {
        throw error;
      }
    }

    const delay = baseDelayMs * 2 ** attempt;
    await wait(delay);
  }

  throw new Error("Request failed after all retry attempts.");
}

This example uses exponential backoff, but it does not attempt to interpret every server-specific header. If an API supplies a retry delay, follow its documented behavior. Add jitter in clients with many concurrent requests so they do not all retry at the same instant.

What to double-check

  • HTTP status: Confirm that every request checks response.ok or handles expected status codes explicitly.
  • Response format: Inspect the content type before calling json(), especially for empty responses and error pages.
  • Request body: Use JSON.stringify() for JSON and set Content-Type only when the body matches it.
  • Authentication: Send credentials according to the API's documented method. Never place secret tokens in a URL where they may enter logs, history, or analytics data.
  • CORS: A browser request can be blocked by the server's cross-origin policy before JavaScript can read the response. Changing fetch syntax does not grant permission; the server and deployment arrangement must support the requested origin.
  • Cancellation: Abort requests when a component unmounts, a route changes, or a newer search supersedes an older one.
  • Observability: Log a request identifier, endpoint category, status, and timing where appropriate, but remove access tokens, passwords, and personal data from logs.

For related API work, keep request payloads documented in the same repository as the client code. Consistent examples make it easier to compare a failing response with the expected schema.

Common mistakes

Assuming catch handles 404 or 500

A non-2xx response usually reaches the next line after fetch(). Without an explicit status check, application code may treat an error document as valid data.

Parsing the body twice

Calling response.json() and then response.text() on the same response commonly fails because the body has already been consumed. Read it once and return a normalized result.

Retrying every error

Authentication failures, validation errors, and most not-found responses are not fixed by repetition. Retries can also duplicate side effects. Limit them to selected transient conditions and safe operations.

Using a timeout without cancellation ownership

A timeout is useful, but a request can also become obsolete because the user navigated away or changed a filter. Pass an AbortSignal through helper functions so the feature that owns the request can cancel it.

Confusing CORS with a server outage

A browser console message about a blocked cross-origin response does not prove that the API is unavailable. Test the endpoint from an appropriate server-side environment and inspect the server's allowed-origin configuration.

When to revisit

Return to this checklist whenever you integrate a new endpoint, change authentication, introduce a proxy, or move a request between browser and server code. Recheck it before a seasonal planning cycle or any release that changes deployment origins, caching, rate limits, or response schemas.

Also revisit fetch utilities when browser APIs or application requirements change. Confirm how your supported environments handle AbortController, external cancellation signals, and any newer timeout helpers before replacing a tested implementation. Review retry rules whenever an API adds rate limiting, idempotency keys, or a documented retry-delay header.

Before shipping, run this short sequence:

  1. Test a successful response and a valid empty response.
  2. Test a malformed JSON response and a plain-text error response.
  3. Test representative 4xx and 5xx statuses.
  4. Cancel a request while it is pending and verify that the UI does not update afterward.
  5. Simulate a network failure and confirm that retries stop at the configured limit.
  6. Verify that logs and error messages do not expose credentials or sensitive payloads.

That process turns a copy-paste fetch example into a dependable API boundary: explicit about failure, bounded in time, safe to cancel, and cautious about repeating work.

Related Topics

#javascript#fetch-api#apis#web-development#debugging
T

The Code Website Editorial Team

Developer Resources Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.