JavaScript Fetch and Asynchronous Requests
Request data with fetch, handle errors and timeouts properly, and run several calls at once.
Key takeaways
-
fetchreturns a promise, andawaitpauses your function until it settles without freezing the page. - Check
response.okorresponse.status, because HTTP error codes don't reject the promise. - Reading the body, for example with
response.json(), is a second asynchronous step. - Add a timeout and handle failures so a stalled request doesn't leave users waiting.
- Cross-origin requests are subject to CORS, which the other server controls.
fetch is the standard way for JavaScript to request data over HTTP. You give it a URL, wait for the response, check that it succeeded, and read the body. Because the network takes time, fetch is asynchronous: it hands back a promise immediately, and your page stays responsive while the answer is on its way.
The detail that trips up most people is that an HTTP error such as 404 or 500 doesn't make fetch fail by itself. You have to check.
Why asynchronous
JavaScript in a page runs largely on one main thread, which also handles clicks and screen updates. If a request blocked that thread, the page would freeze until the server replied. Instead, the browser does the network work separately and notifies your code later.
A promise is an object standing for a result that isn't ready yet. It ends up either fulfilled with a value or rejected with an error. The async and await keywords let you write promise-based code that reads from top to bottom.
A first request
async function loadItems() {
const response = await fetch("https://api.example.com/items");
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
const items = await response.json();
return items;
} response.ok is true for status codes from 200 to 299. The response object arrives as soon as the status and headers are in; the body may still be downloading, which is why reading it needs its own await.
Other body readers include text(), blob(), arrayBuffer() and formData(). A body can normally be read only once; call response.clone() first if you need it twice.
Sending data
The second argument sets the method, headers and body.
const response = await fetch("https://api.example.com/items", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Lamp" })
}); JSON.stringify turns an object into JSON text, and the header tells the server how to read it. When sending a FormData object, such as for file uploads, don't set the content type yourself; the browser adds it with the required boundary.
For query strings, build them safely instead of concatenating:
const url = new URL("https://api.example.com/search");
url.searchParams.set("q", "desk lamp");
fetch(url); That takes care of URL encoding.
Handling errors
There are three different things that can go wrong, and each needs its own handling.
Wrap the call in try and catch:
try {
const items = await loadItems();
render(items);
} catch (error) {
console.error(error);
showMessage("Could not load items. Please try again.");
} Here render and showMessage stand for your own functions. Show people a clear message and a way to retry; keep technical detail for logs. If a response is empty, as with status 204, calling json() will throw.
Timeouts and cancellation
Don't rely on the browser's own patience. Modern browsers support a timeout signal:
const response = await fetch(url, {
signal: AbortSignal.timeout(8000)
}); For manual cancellation, such as when a user types a new search before the last one returned, use an AbortController:
let controller;
async function search(term) {
controller?.abort();
controller = new AbortController();
const url = "/search?q=" + encodeURIComponent(term);
const response = await fetch(url, { signal: controller.signal });
return response.json();
} The aborted call rejects with an error you can recognize by its name, AbortError, and ignore. A timeout from AbortSignal.timeout is reported as TimeoutError. Cancellation also prevents old results from overwriting newer ones.
Several requests at once
Awaiting requests one after another adds their waiting times together. If they don't depend on each other, start them together:
const [userRes, ordersRes] = await Promise.all([
fetch("/api/user"),
fetch("/api/orders")
]); Promise.all rejects as soon as any of its promises rejects. Promise.allSettled waits for all and reports each outcome, which suits a dashboard where one failed panel shouldn't blank the others. Remember to check ok on each response.
For hundreds of items, don't fire everything at once. Process in small batches, or better, ask for an API endpoint that handles many records together. Servers may answer eagerness with 429 Too Many Requests.
Retrying
Temporary failures are worth retrying with increasing delays and a firm limit. Repeating a read is generally safe. Repeating a request that creates an order or takes payment is not, unless the API offers an idempotency mechanism. Retries, backoff and idempotency explains how to do it without causing duplicates.
A reusable helper
Repeating the same checks around every call invites mistakes. Many projects wrap fetch once:
async function getJson(url, options = {}) {
const response = await fetch(url, {
signal: AbortSignal.timeout(8000),
...options,
headers: { Accept: "application/json", ...options.headers }
});
if (!response.ok) {
const error = new Error(`HTTP ${response.status}`);
error.status = response.status;
throw error;
}
if (response.status === 204) return null;
return response.json();
} Callers can now handle one kind of rejected promise and look at error.status when it matters. A 401 might send the user to sign in, a 404 might show an empty state, and a 500 might offer a retry. Keep the helper small. If it grows to hide every detail, debugging gets harder.
How the order of execution works
Code after an await runs later, but other code doesn't wait for it. This surprises people who write:
let items;
loadItems().then(result => { items = result; });
console.log(items); // undefined The log runs before the response has arrived. Put the code that needs the data inside the then callback, or after an await in an async function. At the top level of a JavaScript module, await can be used directly.
A related trap is forEach with an async callback: forEach doesn't wait for the promises. Use a for...of loop to run steps one at a time, or map combined with Promise.all to run them together.
Cookies, credentials and CORS
By default, fetch sends cookies to the same origin only. Setting credentials: "include" sends them cross-origin too, subject to the browser's cookie rules and the server's explicit permission.
An origin is the combination of scheme, host and port. When a page requests another origin, the browser lets your script read the response only if that server allows it through CORS headers. For some requests it first sends a preflight OPTIONS request to ask. You can't fix a CORS error from front-end code; the server has to permit your origin. Setting mode: "no-cors" gives an unreadable response and is rarely what you want. See CORS explained.
Never put private API keys in browser code. Anyone can read them. Route such calls through your own server.
Fetch and older approaches
Earlier code often uses XMLHttpRequest, which works through events and callbacks. It remains supported, and it still offers upload progress reporting in a straightforward way. For most new work, fetch is simpler. Download progress with fetch is possible by reading response.body as a stream, which also lets you handle large or continuously arriving data in pieces.
For messages that the server sends whenever it likes, repeated fetching is wasteful. WebSockets and server-sent events are designed for that.
Caching and fresh data
fetch uses the browser's HTTP cache according to the server's headers, so a repeated request may be answered without a trip across the network. That's normally good. If you see stale data, first check which Cache-Control headers the server sends. The cache option, for instance cache: "no-store", overrides the behavior for a particular call, but fixing the server's headers helps every client.
Your own code can hold on to results too. If two parts of a page need the same data, share one promise instead of sending two requests. Decide how long the copy stays valid and refresh it after the user changes something, or the screen will quietly contradict the server.
Debugging a request
Open the network panel before reproducing the problem. Select the request and check, in order, the address and method, the status, the request headers and body, then the response. A request that never appears points to code that didn't run. One that appears with the wrong address usually means a relative URL resolved against a different page than you expected. Replaying the same call with a command-line tool tells you whether the server behaves differently outside the browser, which helps separate cookie and cross-origin issues from server bugs.
Updating the page responsibly
Show a loading state, disable the submit button while a request is in flight, and restore it in a finally block so it comes back after errors too. Insert returned text with textContent, as described in the DOM explained, since data from an API shouldn't be treated as safe markup.
Then test the unhappy paths. Developer tools can simulate a slow or offline network, and the network panel shows each request, its status and timing. An interface that behaves well when things fail is the one people trust.