Community JavaScript Snippet

The Fetch Wrapper I Keep in Every Project

My zero-dep `apiFetch` for Node and the browser. Adds a per-request timeout, retries with jittered backoff on 5xx and network failures, parses JSON, and attaches an auth token without leaking it into errors.

The Fetch Wrapper I Keep in Every Project

My zero-dep `apiFetch` for Node and the browser. Adds a per-request timeout, retries with jittered backoff on 5xx and network failures, parses JSON, and attaches an auth token without leaking it into errors.

JavaScript
Frontend
4 snippets
http
error-handling
code-template
utility
leoeriksson

By @leoeriksson

April 13, 2026

·

Updated May 18, 2026

1,033 views

32

4.2 (9)

This is the smallest version of the wrapper I will tolerate in a service. The AbortController plus setTimeout pair is the only portable way to bound a fetch call in both Node 18+ and browsers, and clearTimeout in finally matters: if you forget it, an abort fires after the request already returned and you get spurious noise in your logs. safeParseJson exists because real APIs return HTML error pages on 502, and a top-level JSON.parse throw is much harder to debug than a { raw: '...' } payload. The custom ApiError carries status and code separately so callers can branch on err.status === 429 without string-matching the message.