Fetch

suggest change

The Fetch API sends HTTP requests and returns a Promise<Response>. It is available in modern browsers, workers, and current Node.js releases.

Basic request

async function loadUser(id, { signal } = {}) {
  const response = await fetch(`/api/users/${encodeURIComponent(id)}`, { signal });

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
  }

  return response.json();
}

fetch() rejects for failures such as a network error or cancellation. HTTP error responses—including 404 and 500—still fulfill the promise, so check response.ok or response.status explicitly.

Request options

const response = await fetch('/api/items', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'example' }),
  credentials: 'same-origin',
  signal: AbortSignal.timeout(5_000),
});

Common options include:

Option Purpose
method HTTP method; defaults to GET
headers A Headers object or object containing request headers
body Request payload, such as a string, Blob, FormData, or stream; unavailable for GET and HEAD
cache Cache behavior, such as default, no-store, reload, or no-cache
mode Cross-origin mode: cors, same-origin, or no-cors
credentials Credential behavior: omit, same-origin, or include
redirect Redirect behavior: follow, error, or manual
signal An AbortSignal used to cancel or time out the request

An AbortController can cancel several related requests. AbortSignal.timeout() is convenient when the runtime supports it; otherwise, create a controller and call abort() from a timer.

The response body is consumed asynchronously with methods such as json(), text(), blob(), or arrayBuffer(). A body normally cannot be consumed twice unless the response is cloned first.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents