Use the Fetch API to make HTTP requests directly from browser JavaScript. Its fetch() function takes a URL and optional request settings, then returns a Promise for a Response. Requests and responses are first-class objects; a client library is not required for common JSON endpoints. section 12.1 section 12.1.1 section 2.1.2
A successful fetch() call does not necessarily mean a successful HTTP request. The Promise resolves for responses such as 404 or 500, so check response.ok or response.status before using the body. It rejects for lower-level failures, including network errors and cancellation. section 12.1.1
Read a JSON endpoint
For /api/books/42, await fetch(url), throw an error if !response.ok, then await response.json() to obtain the book. A small requestJSON(url, options) helper can centralize the Accept header, status check and JSON parsing. The fetch() Promise resolves when response headers arrive; json() waits to read and parse the body. A consumed body cannot be read again unless it was cloned first. section 12.1.1 section 12.1
Listing 12.1 A reusable helper for JSON requests
async function requestJSON(url, options = {}) {
const { headers, ...fetchOptions } = options;
const response = await fetch(url, {
...fetchOptions,
headers: {
Accept: "application/json",
...headers,
},
});
if (!response.ok) {
throw new Error(`Request failed with ${response.status}`);
}
return response.json(); #1
}
The reusable JSON helper keeps request options separate from its default Accept header, checks the HTTP status and returns the parsed body. section 12.1.1
Make request behavior explicit where the feature needs it:
- Choose a suitable body: JSON for API payloads or FormData for forms and files. Handle cancellation with AbortController or AbortSignal helpers, and represent loading, empty and error states in the UI. section 12.5
- Choose credentials deliberately. Same-origin requests usually send cookies; cross-origin credentials require credentials: "include" and server CORS support. Use "omit" when credentials must not be sent. section 12.1.3
- Stream a response when a download or incremental display cannot wait for the full body. Content-Length can support approximate download progress, but compression can distort the ratio. For precise upload progress, XMLHttpRequest remains a practical choice. section 12.1.8 section 12.5
Treat Fetch as the default for ordinary HTTP request-and-response work, not every network feature. WebSockets serve persistent, bidirectional communication instead. Build on stable browser APIs and add less widely available capabilities only when requirements justify them. section 2.1.2 section 2.2.1

