The Fetch API: A Practical Guide
fetch is the modern way to make an HTTP request in the browser. Learn the response handling, the errors, the abort, and the streaming.
By Velloreth
The basic request
const response = await fetch('https://api.example.com/users');
const data = await response.json();
fetch returns a promise that resolves with a Response object.
The body is read separately, with json(), text(), blob(), or arrayBuffer().
The status trap
// Wrong: this does not throw on a 404
const response = await fetch('/api/missing');
const data = await response.json(); // throws a JSON parse error
fetch resolves even on a 404 or a 500. The promise rejects only on a network failure, such as a DNS error or a dropped connection.
The fix:
const response = await fetch('/api/users');
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
response.ok is true for a status in the 200–299 range.
This is the most common fetch bug. A 500 response is a successful HTTP exchange, so the promise resolves and the error is silent until the body fails to parse.
A POST with JSON
const response = await fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: 'Alice' }),
});
JSON.stringify is required, because the body must be a string or a BodyInit type.
The Content-Type header is required, or the server may not parse the body.
A FormData body sets the content type automatically:
const form = new FormData();
form.append('name', 'Alice');
form.append('photo', fileInput.files[0]);
await fetch('/api/users', { method: 'POST', body: form });
Do not set Content-Type for a FormData body, because the boundary is generated and a manual header breaks it.
Reading the body once
const response = await fetch('/api/users');
const data = await response.json();
const text = await response.text(); // throws: body already read
The body is a stream and can be read only once.
The fix is clone():
const response = await fetch('/api/users');
const clone = response.clone();
const data = await response.json();
const text = await clone.text();
A clone buffers the body, so it is not free for a large response.
Cancelling a request
const controller = new AbortController();
fetch('/api/search?q=hello', { signal: controller.signal })
.then((r) => r.json())
.catch((err) => {
if (err.name === 'AbortError') return; // expected
throw err;
});
// Cancel it
controller.abort();
The use case is a search input. A keystroke starts a request, and the previous one is cancelled so a stale response cannot overwrite a newer one.
let controller;
async function search(query) {
controller?.abort();
controller = new AbortController();
const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
signal: controller.signal,
});
return response.json();
}
AbortSignal.timeout(5000) is the modern way to add a timeout:
fetch('/api/slow', { signal: AbortSignal.timeout(5000) });
Without a timeout, a request can hang indefinitely, which is a real problem on a flaky network.
Credentials
fetch('/api/me', { credentials: 'include' });
same-origin is the default: a cookie is sent only to the same origin.
include sends a cookie on a cross-origin request, and it requires the server to allow the origin with Access-Control-Allow-Credentials.
omit never sends a cookie.
Error handling
async function getUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
if (response.status === 404) return null;
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (error) {
if (error.name === 'AbortError') throw error;
if (error instanceof TypeError) {
throw new Error('Network error — check your connection');
}
throw error;
}
}
A TypeError is a network failure, a CORS failure, or an invalid URL.
An AbortError is a cancellation, which is usually expected and should not be shown to the user.
A JSON parse error is a SyntaxError, which usually means the server returned HTML instead of JSON, such as an error page.
Streaming a response
const response = await fetch('/api/large');
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log(decoder.decode(value, { stream: true }));
}
The response is a stream, so a large body can be processed in chunks rather than buffered.
This is how a server-sent event or a streaming LLM response is read.
response.body is null for a HEAD request or a 204 response.
fetch in a real application
The difference between a fetch call in a tutorial and one in an application is the amount of surrounding code, and the surrounding code is where the bugs live. A real call needs a base URL from the configuration, an authentication header from the session, a timeout, a retry for a transient failure, a cancellation when the component unmounts, and a consistent error shape for the caller. The pattern that keeps it manageable is a single wrapper function that adds the base URL, the headers, the timeout, and the error handling, so a call site is one line. The second pattern is a typed response, so the caller knows the shape of the data and a change to the API is a compile error rather than a runtime surprise. The third is a cancellation on unmount, because a state update after a component has unmounted is a warning at best and a bug at worst.
Streaming a response
A large response does not have to be buffered in memory, and the streaming API is what makes that possible. The response body is a readable stream, and reading it in chunks lets an application process a large file or a server-sent event feed without holding the whole thing. The pattern is to get a reader from the body, read a chunk at a time, decode it, and append it to the output. The practical use cases are a progress indicator for a large download, a log viewer that shows lines as they arrive, and a chat interface that renders a token as it is generated. The detail that catches people out is the decoder: a chunk can split a multi-byte character, so the decoder must be created with the stream option rather than decoding each chunk independently.
Practical guidance
- Check
response.okbefore reading the body. - Set
Content-Typefor a JSON body. - Do not set
Content-Typefor aFormDatabody. - Read the body once, or clone it.
- Use an
AbortControllerto cancel. - Add a timeout with
AbortSignal.timeout. - Handle a
TypeErroras a network error. - Handle an
AbortErroras an expected cancellation. - Use
credentials: 'include'for a cross-origin cookie.
For the related guides, see promises-vs-async-await and cors-explained. For the broader context, api-error-responses-guide and api-pagination-patterns.
Quotable summary
fetch returns a promise that resolves even on a 404 or a 500, so the status must be checked with response.ok, because a 500 response is a successful HTTP exchange and the error is otherwise silent until the body fails to parse. The response body can be read only once, so a second read throws and a clone is needed if it must be read twice. An AbortController cancels a request, which is how a search input avoids a stale response overwriting a newer one, and AbortSignal.timeout adds a timeout so a request cannot hang indefinitely. A network failure rejects the promise with a TypeError while an HTTP error does not, and an AbortError is a cancellation that is usually expected and should not be shown to the user.