JavaScript Reference ยท Browser and Web APIs
The fetch() function
Reference for fetch(): request options, reading JSON and text, checking response.ok, handling network errors, aborting requests and sending data.
fetch() starts an HTTP request and returns a promise for the server's Response. You pass a URL (or a Request object) and an optional options object that sets the method, headers, body, credentials and more. Once the headers arrive, the promise resolves; you then read the body with response.json(), response.text() and friends, each of which returns another promise.
The most important rule: fetch() rejects only when the request itself fails (no network, DNS error, blocked by CORS, aborted). A 404 or 500 response is a successful fetch from the promise's point of view, so you must check response.ok or response.status yourself.
const response = await fetch("/api/users/1"); if (!response.ok) throw new Error("HTTP " + response.status); const user = await response.json();
Try it
The preview sandbox has no network access, so this example uses a small stand-in function that returns real Response objects. The code that handles them is exactly what you would write for a real fetch().
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
fetch(resource) fetch(resource, options)
Typical real-world calls (read-only here, because the sandbox cannot reach a server):
// POST JSON const res = await fetch("/api/notes", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: "Hello" }), }); // Cancel after 5 seconds const slow = await fetch("/api/report", { signal: AbortSignal.timeout(5000) }); // Upload a form (the browser sets the multipart header itself) await fetch("/upload", { method: "POST", body: new FormData(form) });
| Name | Description |
|---|---|
resource |
A URL string, a URL object or a Request. Relative URLs resolve against the page. |
options.method |
"GET" (default), "POST", "PUT", "PATCH", "DELETE", and so on. |
options.headers |
A plain object, an array of pairs or a Headers object. |
options.body |
A string, FormData, URLSearchParams, Blob, ArrayBuffer or a stream. Not allowed with GET or HEAD. |
options.credentials |
"same-origin" (default), "include" or "omit": whether cookies are sent. |
options.mode |
"cors" (default), "same-origin" or "no-cors". |
options.cache |
HTTP cache behavior such as "no-store" or "reload". |
options.redirect |
"follow" (default), "error" or "manual". |
options.signal |
An AbortSignal that cancels the request. |
Return value: a promise for a Response.
Exceptions: the promise rejects with a TypeError for network failures, CORS failures and invalid options, and with an AbortError (or TimeoutError for AbortSignal.timeout()) when cancelled.
Usage notes
- Check
response.ok(true for statuses 200-299). Without it, an error page may be parsed as data. - Read the body once. Call
response.clone()first if two readers need it. - JSON bodies need a header. Set
Content-Type: application/json, or many servers will not parse the body. - Do not set
Content-TypeforFormData. The browser adds the boundary for you. - No timeout by default. Use
AbortSignal.timeout(ms)or anAbortController. - Cookies and CORS. Cross-origin requests need server permission, and cookies are sent only with
credentials: "include"plus matching server headers. - No upload progress.
fetch()exposes download streaming throughresponse.body, but not a simple upload progress event. - Wrap repeated code in a helper that checks
ok, parses JSON and throws a useful error.
Browser support
fetch() is supported in every current browser and in Node.js. Newer pieces such as AbortSignal.timeout() and streaming request bodies are more recent, so check a compatibility table for those.