`fetch`
fetch is the standard function for HTTP in browsers and Node. It returns a promise for a Response. Network failure rejects; HTTP 404 does not.
Detailed Explanation
fetch(url, options) sends a request. The promise fulfills with a Response when the server answers, including 4xx and 5xx. You check res.ok (status 200–299) or res.status. The body is a stream: res.json(), res.text(), res.blob(), res.arrayBuffer() each consume it once.
Default credentials in the browser is same-origin: cookies go to your origin, not to other sites. credentials: "include" sends cookies cross-origin if CORS allows Access-Control-Allow-Credentials. mode: "cors" is the default for cross-origin URLs.
headers, method, body (string, FormData, Blob, URLSearchParams, ReadableStream) are the usual options. JSON.stringify plus Content-Type: application/json is the JSON POST. Do not set Content-Type on FormData; the browser adds the boundary.
Cancel with AbortController. Pass signal in options. Abort rejects with AbortError. Pair fetch with Promise.race only if you also abort() so the request does not keep running.
Node 18+ has global fetch (undici). Older Node needs a polyfill. fetch is not XMLHttpRequest: no upload progress on the simple path (use XHR or streams), and the API is promise-based.
What it costs you: treating any fulfilled promise as success, forgetting CORS, and not aborting on unmount. A 401 is a successful fetch and an empty json() can throw if the body is not JSON.
Reach for fetch for HTTP. Reach for a facade that checks ok and parses once. Reach for XHR only for upload progress in older browsers.
keepalive: true lets a fetch outlive the page (send-beacon-style analytics on unload). The body size is capped. cache: "no-store" is what you want for authenticated JSON that must not sit in the HTTP cache. head requests still need CORS.
When you wrap fetch, preserve the ability to pass signal and headers through. A facade that drops the caller’s AbortSignal is why SPAs keep running requests after navigate.
Code Examples
async function getUser(id, signal) {
const res = await fetch(`/api/users/${id}`, {
headers: { Accept: "application/json" },
signal,
});
if (!res.ok) throw new Error(`http ${res.status}`);
return res.json();
}async function saveUser(user) {
const res = await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(user),
});
if (!res.ok) throw new Error(`http ${res.status}`);
return res.json();
}const ac = new AbortController();
const p = getUser(7, ac.signal);
ac.abort();
p.catch((err) => console.log(err.name)); // => AbortErrorCommon Gotchas
404/500 do not reject
check `res.ok`. Then parse. A HTML error page will fail `res.json()`.
The body can be read once
a second `res.json()` throws. Clone with `res.clone()` if you need two reads.
Cross-origin `fetch` without CORS fails in the browser
the promise rejects with a TypeError and you cannot read the status.