fetch() looks simple — one function, one URL, done. But the same five mistakes show up in almost every beginner codebase I review, and each one fails silently. Here they are, with the one-line fix for each.
1. Trusting the response without checking it
fetch() only rejects when the request could not be made at all. A 404 or 500 still resolves, so code like this prints garbage instead of an error:
const res = await fetch('/api/users/9999');
const user = await res.json(); // {} — no error, just wrong data
Fix: check response.ok (true only for 200–299) before touching the body:
if (!res.ok) throw new Error(`HTTP ${res.status}`);
2. POSTing JSON without the Content-Type header
Sending an object without JSON.stringify() and the header means the server receives [object Object] or rejects the body outright.
Fix:
await fetch('/api/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title, body }),
});
3. No timeout — the request that never ends
fetch() waits forever by default. One slow server and your UI freezes.
Fix: one line with AbortSignal.timeout():
const res = await fetch(url, { signal: AbortSignal.timeout(8000) });
4. Awaiting requests one after another
Two independent requests awaited in sequence take double the time.
Fix: start them together with Promise.all():
const [user, posts] = await Promise.all([
fetch('/api/users/1').then(r => r.json()),
fetch('/api/users/1/posts').then(r => r.json()),
]);
5. Calling .json() on a response that isn't JSON
A 204 No Content or an HTML error page makes .json() throw a confusing SyntaxError.
Fix: check the content type first, or use .text() when you are not sure what came back:
const type = res.headers.get('Content-Type') || '';
const data = type.includes('application/json') ? await res.json() : await res.text();
None of these mistakes throws a loud error — that is exactly why they survive in production. The response.ok check alone would have saved me hours when I was starting out.
I wrote a full step-by-step tutorial with working code for GET, POST, PUT, DELETE, auth headers, timeouts, and parallel requests here: https://rajadevsolutions.online/blog/how-to-use-javascript-fetch-api-to-call-a-rest-api
It uses a free practice API, so you can run every example in your browser console right now.
Top comments (0)