The browser’s fetch() API returns a promise for an HTTP response. A fulfilled promise does not necessarily mean the server returned a successful status, so check response.ok before using the response body.
A small reusable example
async function loadProfile(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
loadProfile("/api/profile")
.then((profile) => console.log(profile))
.catch((error) => console.error("Could not load profile:", error));
The endpoint must permit the request under the browser’s same-origin and CORS rules. Do not place private API keys in client-side JavaScript.
Render data safely
Treat remote values as data, not HTML. Prefer assigning text with textContent:
const heading = document.querySelector("h1");
heading.textContent = profile.displayName;
Avoid interpolating untrusted values into innerHTML, which can create cross-site scripting vulnerabilities.
Add cancellation when needed
For a request that may outlive the page or a newer search, pass an AbortSignal through AbortController. Handle cancellation separately from unexpected network errors when the user experience needs different messaging.