fetch
Requests a URL and returns a promise for the response — rejects only on network failure, not on an HTTP error status.
fetch(url, options?) => Promise<Response>
Purpose
fetch requests a URL and returns a promise that resolves to a Response object once the response
headers have arrived (the body may still need to be read separately).
Syntax
async function getUser(id) {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json(); // itself returns a promise
}
// A POST request with a JSON body
await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Ada' }),
});
Behavior notes
fetch’s promise rejects only for a network-level failure (offline, DNS error, blocked by CORS before a response is received) — an HTTP error status like 404 or 500 still resolves normally.response.ok(true for status 200–299) orresponse.statusis how a failed request is actually detected.- Reading the body —
response.json(),response.text(),response.blob()— returns its own promise and can only be called once per response; the body stream is consumed after the first read. - By default,
fetchdoes not send cookies to a cross-origin request;credentials: 'include'is needed for that, subject to the target server’s CORS configuration.
Common mistakes
- Treating any resolved
fetchpromise as success without checkingresponse.ok. - Calling
response.json()on a response that isn’t actually JSON (an HTML error page from a misconfigured endpoint, for instance) — this throws aSyntaxErrorfrom the JSON parser, which can look confusingly unrelated to the real problem. - Forgetting to
awaitboth thefetch(...)call and the subsequentresponse.json()call — both return promises.
Runtime notes
Standard in every current browser; available as a global in Node 18 and later without an added library.