Back to Explore
GuideVibeFix editorialUpdated Nov 20, 2026

Stop letting requests fail quietly: the Fetch API, explained plainly

The order page fetches the menu and submits orders, and it all runs on fetch(). This guide follows MDN's Using the Fetch API guide: the default GET, why a 404 does not reject, five ways to read the body, POSTing JSON, request headers, the three cross-origin modes, the three credential settings, canceling requests, single-read bodies, and streaming.

Real photo: a row of black server racks in a data center, dense grey-blue network cables tangled between them

First, the boundaries of this guide. The site already has a practical guide to CORS, about how the server sets headers and how preflight works; a practical guide to API resilience with circuit breakers, about retrying failed requests and breaking the circuit; a practical guide to Promises and async/await, about the ways to write code that waits for a result to come back; and a practical guide to the event loop, about when code actually runs. This guide is about none of those. It is about one thing only: how to write the fetch() call in the browser, what goes out, and what comes back. The "Greenstone Cafe" used below is still the same fictional practice project: a small web tool that takes orders for a street-side cafe. This time it is about its order page: the page fetches the menu from the backend, submits orders, and cancels a request sent by mistake. Every operation, code sample, and number built around it was invented to explain the technique, not a real record. All syntax and behavior of Fetch comes from MDN's Using the Fetch API guide, see each article's meta information and evidence record for sources. The guide's own examples, such as example.org, products.json, and the username "example", are the documentation's examples, not real services.

Step 1: The shortest fetch() call is a GET by default

The shortest way to make a request is one line: const response = await fetch("https://example.org/products.json"). MDN puts it this way: to make a request, call fetch(), passing in a definition of the resource to fetch, which can be a URL string, a URL object, or a Request instance; with no second argument, the default is a GET request. fetch() returns a Promise, and the browser fulfills it with a Response object as soon as it has received the response status and headers — note that the response body may not have arrived yet, so the status and headers come first and the body comes later. The cafe's order page fetches the menu exactly this way: const response = await fetch("/api/menu"), one line to send it, and response is the receipt for that request. Remember the first sentence: fetch() is a GET by default, and what you get when it fulfills is the receipt — the Response — not data that has already been read.

Step 2: A 404 does not reject fetch — check ok before reading data

This is the easiest trap in Fetch, and MDN gives it a paragraph of its own: the promise returned by fetch() rejects only on errors such as a network error or a bad scheme; if the server responds with an error status such as 404 or 500, the promise still fulfills with a Response. In other words, the request went out and the server answered, and even when the answer is "there is no such thing", fetch still counts it as success. So before reading data you must check the status: response.status is the numerical status code, and response.ok is true only when the status is in the 200 to 299 range. MDN's usual pattern is: if (!response.ok) { throw new Error(`Response status: ${response.status}`); } — stop error statuses at the door and throw, then read on. The cafe's order page stepped into this trap: the menu endpoint went down and returned 404, the frontend never checked ok, it called response.json() on the 404 page content, JSON parsing failed, and the page showed "parsing failed" while the real cause — "the endpoint is gone" — was covered up. Remember the test: a fulfilled fetch does not mean a successful request; check ok first, then read the body.

Step 3: Five ways to read the body — pick by content type

The Response interface provides five methods to read the body, all asynchronous methods returning a Promise: arrayBuffer(), blob(), formData(), json(), and text(). Which one to use depends on what the content is: json() for JSON data, text() for plain text, blob() for an image that you then turn into a local URL, formData() for form data, and arrayBuffer() for binary data. MDN has a complete example for fetching an image: const response = await fetch("flowers.jpg"), check ok first, then const blob = await response.blob(), then const objectURL = URL.createObjectURL(blob), and finally image.src = objectURL, and the image shows. A blob suits binary content such as images and files — read it, then hang it on the page with URL.createObjectURL, without turning the whole image into text first. A method will throw an exception if the response body is not in the appropriate format — calling json() on something that is not JSON throws on parsing. So the safe way is to look at the response headers before reading: const contentType = response.headers.get("content-type"); if (!contentType || !contentType.includes("application/json")) { throw new TypeError("Oops, we haven't got JSON!"); } — that is MDN's fetchJSON example, verbatim. The cafe's order submission is written this way: it first confirms that content-type contains application/json, then calls response.json(), so when the backend occasionally returns a plain-text error, the frontend can report "what came back is not JSON" instead of a vague parsing error. Remember the test: look at the content type first, then pick how to read; json() only reads real JSON.

Step 4: POSTing JSON needs all three pieces

The default is GET; to send a POST, write method in the second argument. MDN's example is: const response = await fetch("https://example.org/post", { method: "POST", body: JSON.stringify({ username: "example" }), headers: { "Content-Type": "application/json" } }). All three pieces are required: method tells the server what action this is, body is the payload going over, and Content-Type tells the server what format the payload is in. Note that the body must already be a string: JSON.stringify turns the object into a string before it is sent; if you pass the object straight to body, MDN says other objects are converted to strings using their toString() method, and the result is "[object Object]" — a useless string the server cannot use. The cafe submits orders exactly this way: body: JSON.stringify({ dish: "latte", count: 2 }), with Content-Type: application/json in the headers, and the backend parses it as JSON the first time. Remember the test: to POST JSON, have method, body, and Content-Type all present before sending.

Step 5: Two ways to set request headers — a Headers object adds sanitization

Request headers give the server information about the request: in a POST request, for example, the Content-Type header tells the server the format of the request's body. There are two ways to set them: pass an object literal to the headers option, or construct a Headers object, add headers to it with append(), and assign that Headers object to the headers option. MDN says the Headers object provides some additional input sanitization: it normalizes header names to lowercase, strips leading and trailing whitespace from header values, and prevents certain headers from being set. Many headers are set automatically by the browser and cannot be set by a script — these are called forbidden request headers; if the mode option is set to no-cors, the set of permitted headers is further restricted. The cafe's order page uses the object-literal spelling: headers: { "Content-Type": "application/json" }, simple and enough; when headers have to be built up dynamically, or when you want the browser to watch over them one more layer, switch to a Headers object. Remember the test: few headers, use an object literal; many headers, or one more layer of sanitization, use a Headers object; headers the browser sets itself are not yours to change.

Step 6: GET has no body — put parameters in the query string

A GET request cannot include a body, but you can still send data to the server by appending it to the URL as a query string. MDN's way is to encode the data with URLSearchParams and append it to the URL: const params = new URLSearchParams(); params.append("username", "example"); const response = await fetch(`https://example.org/login?${params}`), and the request that goes out is https://example.org/login?username=example. URLSearchParams handles the encoding for you, so spaces, Chinese characters, and special symbols in a username need no hand-coding. The other way around, URLSearchParams can also be the body of a POST request, paired with application/x-www-form-urlencoded, and the server parses it as a form. The cafe's menu filter is written this way: params.append("category", "hot drinks"), appended to /api/menu, and refreshing the list needs no other code change. Remember the test: GET parameters go in the query string, built with URLSearchParams — never hand-write question marks and equals signs.

Step 7: Nine things can be a body — a file goes over as-is

The request body is the payload of the request: the thing the client is sending to the server. MDN lists nine types that can be supplied as the body: a string, ArrayBuffer, TypedArray, DataView, Blob, File, URLSearchParams, FormData, and ReadableStream. Uploading a file means passing the File straight as the body, a form goes as FormData, and binary data goes as ArrayBuffer or TypedArray. The old rule still applies: any other object is converted with toString(), so before passing an object, turn it into a string or a FormData yourself. The cafe's "upload today's special photo" is written this way: the body is the File the user picked, with no extra headers to write — the browser handles it. Remember the test: before passing a body, ask whether it is one of MDN's nine types; if not, convert it first.

Step 8: Three modes govern cross-origin requests — an opaque response shows nothing

Whether a request can be made cross-origin is determined by the RequestInit.mode option, which takes one of three values: cors, same-origin, or no-cors. The default value of mode for fetch requests is cors, meaning that a cross-origin request uses the Cross-Origin Resource Sharing (CORS) mechanism. If the request is a simple request, then the request will always be sent, but the server must respond with the correct Access-Control-Allow-Origin header or the browser will not share the response with the caller; if the request is not a simple request, then the browser will send a preflighted request to check that the server understands CORS and allows it, and the real request will not be sent unless the server responds to the preflight with the appropriate CORS headers. Setting mode to same-origin disallows cross-origin requests completely. Setting mode to no-cors disables CORS for cross-origin requests: methods are restricted to GET, HEAD, and POST, the headers that may be set are restricted, and the response is opaque, meaning that its headers and body are not available to JavaScript. MDN's own words are that most of the time a website should not use no-cors: the main application of it is for certain service worker use cases. Memorize what an opaque response looks like: its status is 0, its header list is empty, and its body is null. This guide covers only the three switches on the fetch side; what headers the server should return and how preflight is configured belong to the CORS guide on this site. Remember the test: use the default cors in everyday work; when you get a response with status 0, ask first whether you went through no-cors.

Step 9: Three credential settings govern credentials — cross-origin credentials need the server to agree

In the context of the Fetch API, a credential is an extra piece of data sent along with the request that the server may use to authenticate the user: HTTP cookies, TLS client certificates, and the Authorization and Proxy-Authorization headers. The credentials option takes one of three values: omit never sends credentials in the request or includes credentials in the response; same-origin, the default, only sends and includes credentials for same-origin requests; include always includes credentials, even cross-origin. But there are two gates. First, if a cookie's SameSite attribute is set to Strict or Lax, then the cookie will not be sent cross-site, even if credentials is set to include. Second, including credentials in cross-origin requests can make a site vulnerable to CSRF attacks, so the server must also agree to their inclusion by including the Access-Control-Allow-Credentials header in its response, and in this situation the server must explicitly specify the client's origin in the Access-Control-Allow-Origin response header — a star is not allowed. Missing any one of these, the browser returns a network error. MDN also splits it into two cases: for a simple request, the request is sent with credentials, but the server must set both headers or the browser returns a network error; for a non-simple request, the browser sends a preflighted request without credentials first, and only follows up with the real request, including credentials, if the server sets the right headers. The cafe's order page, once logged in, calls the order endpoint with credentials: "include", paired with a same-origin order service, and it worked the first time it was written correctly. Remember the test: cross-origin credentials need both sides to agree — the client with credentials: "include", the server with Access-Control-Allow-Credentials, and an origin that is never a star.

Step 10: A Request object can be reused — and derived with one change

The Request() constructor takes the same arguments as fetch() itself: instead of passing options into fetch(), you can pass the same options to the Request() constructor, and then pass that object to fetch(). MDN's example is: const myRequest = new Request("https://example.org/post", { method: "POST", body: JSON.stringify({ username: "example" }), headers: myHeaders }), then const response = await fetch(myRequest). The benefit is reuse: one request definition can be passed around; and derivation: new Request(request1, { body: JSON.stringify({ username: "example2" }) }) copies request1 and changes only the body. MDN's post(request) example uses exactly this: one function takes a Request, calls fetch, reads json, and logs success, and two derived requests are passed in one after another, each running on its own. The cafe's order page wraps "submit order" in a Request template: the base headers and URL are written once, and different orders only change the body. Remember the test: when the same request goes out more than once, build a Request first; to change one thing, derive a new one from the old.

Step 11: Cancel with AbortController — too late still errors

To make a request cancelable, create an AbortController, and assign its AbortSignal to the request's signal property. To cancel the request, call the controller's abort() method, and the fetch() call will reject the promise with an AbortError exception. One controller can also govern several requests: hand the same signal to several fetch calls, press abort once, and all of them stop together — the right shape for "stop all old requests when the category changes". MDN's example uses two buttons: one starts the fetch, the other cancels it; when the cancel button is pressed, controller.abort() runs, and the running fetch rejects at once with AbortError, which the catch block logs as an error. There is one timing that is easy to miss: if the request is aborted after the fetch() call has been fulfilled but before the response body has been read, then attempting to read the response body will reject with an AbortError exception. MDN's get() example is written this way: after const response = await fetch(request), it calls controller.abort(), and then await response.text() throws AbortError on that very line. The cafe's order page uses this trick when the user switches menu categories: the new category is tapped, the old category's request is aborted at once, and the old data can never arrive a step late and cover the new list. Remember the test: a request that can be canceled deserves a signal; cancel early — late, and even reading the body reports AbortError.

Step 12: The body is a stream — read it once, or clone it first

Request and response bodies are actually ReadableStream objects, and whenever you read them, you are streaming the content. The benefit is memory efficiency: the browser does not have to buffer the entire response in memory before the caller retrieves it with a method like json(). The cost is that it can only be read once: if a reader has been attached to a stream using getReader(), then the stream is locked, and nothing else can read the stream; if any content has been read from the stream, then the stream is disturbed, and nothing else can read from the stream. MDN's example is: after const result1 = await response.json(), a second call, const result2 = await response.json(), throws. If you do need to read the body more than once, you must call Response.clone() before reading the body: const response2 = response1.clone(), and the two read separately without interfering. The most common use is implementing an offline cache with service workers: MDN's cacheFirst example checks the cache first, fetches when there is no hit, and when the response is ok, stores the clone with cache.put(request, networkResponse.clone()) and returns the original to the app. Request bodies work the same way: a request with a body sent twice throws "Body has already been consumed.", so clone it before sending it again. This guide covers only the stream rules on the fetch side; how to build offline caching belongs to the offline guide on this site. Remember the test: a body can be read once — decide before reading whether you need a clone.

Step 13: Do not wait for the whole file — stream a large file chunk by chunk

Calling response.text() means waiting until the whole file has been received before you can process any of it, and a large file stalls the page. The streaming way is to take response.body directly, pipe it through a TextDecoderStream, and process each chunk as it arrives with for await: const stream = response.body.pipeThrough(new TextDecoderStream()); for await (const value of stream) { console.log(value); }. MDN notes that when you access the body directly like this, you get the raw bytes of the response and must transform it yourself — here TextDecoderStream decodes the UTF-8-encoded body data as text. The guide goes one step further with an example that reads a text resource line by line: a generator uses a regular expression to look for line endings and yields one line at a time, while a consumer processes each line as it comes. The cafe's order page uses the streaming way for "all of today's orders", a large text payload: one order arrives, one line shows on the page, with no waiting for the whole file. Remember the test: small data, read it in one go with json() or text(); a large file, stream it chunk by chunk.

Step 14: Responses have a type too — look at type before reading headers

The Response also has a type property, which tells you how this response came about, in four kinds: basic means the request was a same-origin request, cors means it was a cross-origin CORS request, opaque means it was a cross-origin simple request made with the no-cors mode, and opaqueredirect means the request set the redirect option to manual and the server returned a redirect status. The type determines what you can see: basic responses exclude response headers from the forbidden response header name list, CORS responses include only response headers from the CORS-safelisted response header list, and opaque responses and opaque redirect responses have a status of 0, an empty header list, and a null body. In other words, the headers of a cross-origin response are not all handed to you; look at response.type first, then decide which headers to read — never look for Content-Type on an opaque response. The cafe's order page saw this property when connecting to a third-party recipe service: the response type was cors, and only the few headers on the safelisted list were visible, so a custom X-Menu-Version could not be read — not because the backend failed to send it, but because under the CORS rules the browser does not hand it over. Remember the test: look at type before reading headers; an opaque response holds nothing at all.

Step 15: 100 request incidents in one month — check yourself against the chart

Bar chart of 100 Fetch request incidents in one month in the fictional Greenstone Cafe project, by cause

The chart above shows a fictional month for the Greenstone Cafe project: 100 incidents related to Fetch requests in total. Forgetting to check ok and treating a 404 as success: 32, or 32.0%, the largest group; reading the body twice, with the second read throwing: 20, or 20.0%; calling json() on non-JSON without checking content-type first: 16, or 16.0%; forgetting Content-Type on a POST, so the backend did not recognize the body: 14, or 14.0%; putting a body on a GET request: 10, or 10.0%; cross-origin credentials not fully configured, so the browser reported a network error: 8, or 8.0%. 32 + 20 + 16 + 14 + 10 + 8 = 100, and the books balance. Each group in the chart maps to a step in this guide: forgetting ok is step 2, reading the body twice is step 12, json() on the wrong format is step 3, a POST without Content-Type is step 4, a body on a GET is step 6, and cross-origin credentials are step 9. These numbers are invented examples, meant to show at a glance that the first group is nearly a third — and that its root cause is only one thing: a fulfilled fetch does not mean a successful request, and ok must be checked first.

Checklist: after writing code with fetch, tick each item

First, fetch() is a GET by default, and what you get when it fulfills is the receipt — the Response — not data that has already been read. Second, a 404 or 500 does not reject fetch — look at response.ok before reading the body, and throw when it is not ok. Third, pick how to read the body by content type: json(), text(), blob(), arrayBuffer(), or formData(), and look at content-type before reading. Fourth, POSTing JSON needs all three pieces: method, a body after JSON.stringify, and Content-Type: application/json. Fifth, few headers go in an object literal, many headers go in a Headers object; headers the browser sets itself cannot be changed. Sixth, GET has no body — build parameters with URLSearchParams and put them in the query string. Seventh, a body only takes the nine types MDN lists; a file goes over as-is, an object must be converted first. Eighth, use the default cors in everyday work; when you get a response with status 0, ask first whether you went through no-cors. Ninth, cross-origin credentials need both sides to agree: the client with credentials: "include", the server with Access-Control-Allow-Credentials, and an origin that is never a star. Tenth, when the same request goes out more than once, build a Request first; to change one thing, derive a new one from the old. Eleventh, a request that can be canceled gets a signal, the cancel button calls abort(), and late, even reading the body reports AbortError. Twelfth, the body is a stream and can be read once — to read it twice, clone it first. Thirteenth, small data is read in one go, a large file is streamed chunk by chunk. Fourteenth, responses come in four types — basic, cors, opaque, and opaqueredirect — and an opaque one has a status of 0, an empty header list, and a null body; look at type before reading response headers. If any item cannot be answered, go back to its section and read it again — that is worth more than memorizing ten more APIs.

Views 3Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photo: a bank of light gray metal filing cabinets with one drawer pulled open, revealing rows of hanging file folders inside
Guide
A real database inside the browser: IndexedDB local storage, explained plainly

localStorage only stores strings and has no indexes. IndexedDB is a real database in the browser: structured data, far larger capacity, indexes, and transactions. Following MDN's Using IndexedDB, IDBDatabase, and IDBObjectStore: the five-step routine, opening, upgrades, keys, indexes, transactions, add versus put, get, cursors, ranges, and multi-tab upgrades.

Tool TipsData WorkflowsFrontend Engineering
Real photo: hands typing on a MacBook Pro showing JavaScript code that changes HTML content, with a white mouse, papers, and binders on a white desk
Guide
Functions without the confusion: JavaScript functions, parameters, and arrow functions, explained plainly

You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.

Tool TipsFrontend EngineeringAI Coding
Real photo: a laptop, tablet, and phone on a wooden table showing the same green-leaf website, the phone view with navigation in one column, a potted plant nearby
Guide
Squashed on phones? Responsive layout and media queries, explained plainly

One page should stand up on a phone, a tablet, and a computer. This guide follows MDN's Responsive web design, Using media queries, and the viewport meta reference: fluid HTML, the viewport tag, fluid grids and max-width, images that never burst their container, media query syntax, breakpoints set by content, mobile first, responsive type, testing capability instead of width, and a pre-launch checklist.

Mobile AppsDesign ExperienceFrontend Engineering