fetch is built in and sufficient. Axios adds interceptors, automatic JSON handling and a timeout option, and on a team already using it there is no reason to switch. What matters more than the choice is handling the cases a phone meets and a desktop browser rarely does.
fetch does not reject on an HTTP error. A 404 or a 500 resolves normally with ok set to false, so without checking response.ok you will parse an error page as data and see a confusing JSON exception instead of the status. And fetch has no timeout by default: on a train with one bar, a request can hang for minutes. Use AbortSignal.timeout to bound it, and pass the signal so the request is actually cancelled.
Put the whole thing behind one small client rather than calling fetch from components. One function that attaches the base URL, the auth header and the timeout, and converts a failure into a typed error, means the retry policy and the token refresh live in one place rather than in forty.
Attach the auth token at request time, not at module load - a token read into a constant when the app started is the wrong token after a refresh.
const BASE_URL = 'https://api.example.com';
export class ApiError extends Error {
constructor(public status: number, message: string) {
super(message);
}
}
type Options = { method?: string; body?: unknown; token?: string };
export async function api<T>(path: string, options: Options = {}): Promise<T> {
const { method = 'GET', body, token } = options;
let response: Response;
try {
response = await fetch(`${BASE_URL}${path}`, {
method,
headers: {
'Content-Type': 'application/json',
// Read at call time. A token captured at module load goes stale.
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
body: body ? JSON.stringify(body) : undefined,
// fetch has NO default timeout. On a weak signal this hangs for minutes.
signal: AbortSignal.timeout(15_000),
});
} catch (error) {
if (error instanceof DOMException && error.name === 'TimeoutError') {
throw new ApiError(408, 'The request took too long.');
}
throw new ApiError(0, 'No connection.');
}
// fetch does NOT reject on 404 or 500. Check it yourself.
if (!response.ok) {
throw new ApiError(response.status, `Request failed (${response.status})`);
}
if (response.status === 204) return undefined as T;
return (await response.json()) as T;
}
Open this example in the editor and change it. Nothing you type is saved.