Sub topic 12
Putting It Together: A Reusable Fetch Helper
The earlier chapters covered each part of fetch on its own: checking response.ok, serializing JSON, building headers, adding timeouts, and reading bodies. In a real application, repeating all of that at every call site leads to duplicated code and small differences between call sites. This chapter combines those pieces into one helper. Callers of the helper get parsed data back when a request succeeds, and they get one predictable set of errors when it fails.
This chapter assumes you have read the earlier chapters on error handling, sending JSON, the Headers interface, and AbortController. It also assumes you know ES modules and async/await. The examples use top-level await, so run them in a module (<script type="module">, a .mjs file in Node 18+, or the browser console).
What the Helper Must Do
Before writing code, list the jobs the helper takes away from callers. Each job fixes a mistake that is easy to make with plain fetch.
| Responsibility | Mistake it prevents with plain fetch |
|---|---|
| Throw on non-2xx statuses | Treating a 404 or 500 as success because the Promise resolved |
| Encode JSON bodies and set `Content-Type` | Sending `[object Object]`, or a body the server cannot parse |
| Apply a default timeout | Requests that hang forever on a stalled connection |
| Parse based on `Content-Type` | Calling `json()` on an HTML error page or an empty 204 body |
| Attach the error body to the error | Losing the server's validation messages |
| Resolve paths against a base URL | Hard-coding hosts across the codebase |
The helper should leave some things alone. It should not hide fetch options such as credentials, mode, or cache, so any option it does not recognize is passed straight through to fetch.
A Typed Error for HTTP Failures
Callers need to tell an HTTP failure apart from a network failure or a timeout. A dedicated Error subclass makes that possible with instanceof, and it carries the status and the parsed error body.
export class HttpError extends Error {
constructor(response, body) {
super(`HTTP ${response.status} ${response.statusText}`);
this.name = 'HttpError';
this.status = response.status;
this.url = response.url;
this.body = body;
}
}Keep body on the error. Many APIs return JSON such as { "errors": { "email": "already taken" } } with a 422 status. If the helper throws before reading the body, that information is lost.
Parsing the Body Safely
Calling response.json() directly causes three kinds of failure:
- A 204 No Content response has no body, so
json()throws aSyntaxError. - A proxy or load balancer may return an HTML error page instead of JSON.
- Some APIs use
application/problem+json(RFC 9457) for errors. A plainincludes('application/json')check misses that type.
Reading the body as text first and then deciding how to parse it handles all three cases:
const JSON_TYPE = /[\/+]json\b/i;
async function parseBody(response) {
if (response.status === 204 || response.status === 205) return null;
const text = await response.text();
if (text === '') return null;
const type = response.headers.get('content-type') ?? '';
return JSON_TYPE.test(type) ? JSON.parse(text) : text;
}The regular expression matches application/json, application/json; charset=utf-8, and application/problem+json. Reading the text first costs very little and lets the helper check for an empty body before parsing. Binary responses such as images or files should not use this helper's parsing. The next section adds a way to skip it.
The Core `request` Function
export async function request(url, options = {}) {
const {
json,
timeout = 10000,
headers,
signal,
raw = false,
...rest
} = options;
const finalHeaders = new Headers(headers);
if (!finalHeaders.has('Accept')) {
finalHeaders.set('Accept', 'application/json');
}
const init = { ...rest, headers: finalHeaders };
if (json !== undefined) {
finalHeaders.set('Content-Type', 'application/json');
init.body = JSON.stringify(json);
}
const timeoutSignal = AbortSignal.timeout(timeout);
init.signal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
const response = await fetch(url, init);
if (raw) {
if (!response.ok) throw new HttpError(response, await parseBody(response));
return response;
}
const body = await parseBody(response);
if (!response.ok) throw new HttpError(response, body);
return body;
}The next three sections explain the design choices in this function.
Why `new Headers(headers)` instead of object spread
The simpler version in the spine merges headers with { Accept: 'application/json', ...headers }. That version breaks silently when a caller passes a Headers instance. A Headers object stores its entries internally and has no own enumerable properties, so spreading it produces {} and drops every header the caller set. The Headers constructor accepts a plain object, an array of pairs, another Headers instance, or undefined. Using it normalizes every input, and it also makes has('accept') case-insensitive.
Why combine signals instead of choosing one
A common shortcut is signal ?? AbortSignal.timeout(timeout). With that shortcut, a caller who passes a signal (for example, to cancel a search when the user types again) loses the timeout. AbortSignal.any() returns a signal that aborts when any of its inputs aborts. The error name still tells the caller which input caused it: TimeoutError comes from the deadline, and AbortError comes from the caller's controller. AbortSignal.any() is supported in Chrome 116+, Firefox 124+, Safari 17.4+, and Node 20.3+.
The `raw` escape hatch
Downloads, streams, and responses where the caller needs headers such as ETag or Link require the Response object itself. With raw: true, the helper still throws on HTTP errors but returns the unread response. This keeps the error contract the same for every request, and callers can still call blob() or body.getReader() themselves.
Adding a Base URL and Method Shortcuts
Most applications talk to one or two APIs. A small factory function fixes the base URL and default headers once:
export function createClient({ baseUrl, headers: defaultHeaders = {}, timeout } = {}) {
function call(method, path, { query, headers, ...options } = {}) {
const url = new URL(path, baseUrl);
if (query) {
for (const [key, value] of Object.entries(query)) {
if (value !== undefined) url.searchParams.set(key, String(value));
}
}
const merged = new Headers(defaultHeaders);
new Headers(headers).forEach((value, key) => merged.set(key, value));
return request(url, { timeout, ...options, method, headers: merged });
}
return {
get: (path, options) => call('GET', path, options),
post: (path, json, options) => call('POST', path, { ...options, json }),
put: (path, json, options) => call('PUT', path, { ...options, json }),
patch: (path, json, options) => call('PATCH', path, { ...options, json }),
delete: (path, options) => call('DELETE', path, options)
};
}timeout is spread before options, so a per-call timeout overrides the client default. If both are undefined, the default parameter in request still applies, because destructuring defaults apply to undefined values.
Using the client:
const api = createClient({
baseUrl: 'https://api.example.com/v1/',
headers: { Authorization: 'Bearer TOKEN' },
timeout: 8000
});
const users = await api.get('users', { query: { page: 2, limit: 20 } });
const created = await api.post('users', { name: 'Ada' });
await api.delete(`users/${created.id}`);Handling Errors at the Call Site
The helper produces four kinds of failure, and each one needs a different response in the UI:
| Error | How to detect it | Typical meaning |
|---|---|---|
| `HttpError` | `err instanceof HttpError` | The server answered with 4xx or 5xx |
| Timeout | `err.name === 'TimeoutError'` | The deadline passed |
| Cancellation | `err.name === 'AbortError'` | The caller aborted on purpose |
| Network failure | `err instanceof TypeError` | Offline, DNS failure, or CORS rejection |
| Bad JSON | `err instanceof SyntaxError` | The server sent a JSON content type with an invalid body |
async function saveUser(data) {
try {
return await api.post('users', data);
} catch (err) {
if (err instanceof HttpError && err.status === 422) {
showValidationErrors(err.body?.errors ?? {});
} else if (err instanceof HttpError && err.status === 401) {
redirectToLogin();
} else if (err.name === 'AbortError') {
// The user cancelled; show nothing.
} else if (err.name === 'TimeoutError') {
showToast('The server is taking too long. Try again.');
} else {
showToast('Network problem. Check your connection.');
console.error(err);
}
return null;
}
}Put the AbortError check before any generic "something went wrong" message. A cancellation the user started should not show up as an error.
Design Decisions and Edge Cases
Retries
Retrying inside the helper looks convenient, but it is risky. Retry only idempotent methods (GET, PUT, DELETE). Retry only on network errors, timeouts, 429, and 503, and honor any Retry-After header. Never retry a POST automatically, because that can create duplicate records. If you add retries, make them opt-in with a per-call option.
Request bodies that are not JSON
FormData, Blob, and URLSearchParams bodies pass through unchanged when given as body. Do not set Content-Type for FormData. The browser has to generate the multipart boundary itself, and a manually set header leaves out the boundary.
Unwanted preflights
The default Accept: application/json is a CORS-safelisted header, so it does not trigger a preflight request on its own. Content-Type: application/json and Authorization do trigger one. If a cross-origin GET suddenly needs an OPTIONS request, check what headers the helper adds by default.
Testing
Because the helper calls the global fetch, tests can replace it with a stub. For example, globalThis.fetch = async () => new Response('{"id":1}', { status: 200, headers: { 'Content-Type': 'application/json' } }) exercises the whole pipeline without a server.
Exercises
Exercise
A caller writes request(url, { headers: new Headers({ 'X-Trace': 'abc' }) }) against the spine's simpler wrapper, which merges headers with { Accept: 'application/json', ...headers }. The server never receives X-Trace. Why, and how does this chapter's version fix it?
Show answer
Spreading a Headers instance copies only its own enumerable properties. Headers stores its entries internally and has no such properties, so the spread produces an empty object and X-Trace is dropped. This chapter's version passes the input to new Headers(headers), which accepts plain objects, arrays of pairs, and Headers instances, so every input form is copied.
Exercise
A search box passes its own AbortController signal to request. Under the spine's options.signal ?? AbortSignal.timeout(timeout) logic, what happens if the server stalls, and how does AbortSignal.any change the result?
Show answer
When the caller supplies a signal, the ?? expression uses only that signal, so no timeout applies and the stalled request hangs until the user types again or the page closes. AbortSignal.any([signal, timeoutSignal]) aborts on whichever fires first: the deadline rejects with a TimeoutError, and a user-triggered cancel still rejects with an AbortError.
Exercise
A client is created with baseUrl: 'https://api.example.com/v2', and api.get('orders') returns 404. What URL was requested, and what is the fix?
Show answer
new URL('orders', 'https://api.example.com/v2') resolves to https://api.example.com/orders, because without a trailing slash the last path segment v2 is treated as a file name and replaced. Set the base URL to https://api.example.com/v2/ and keep paths relative with no leading slash.
Exercise
Extend request so that a 401 response calls an onUnauthorized callback (passed in options) before throwing the HttpError. Where should the call go, and why should the helper still throw?
Show answer
Destructure onUnauthorized from options so it is not passed to fetch. After parseBody and inside the !response.ok branch, add if (response.status === 401) onUnauthorized?.(response), then throw the HttpError as before. The helper should still throw because the caller awaited data it did not receive. Returning normally would let the calling code continue with undefined as if the request had succeeded.