Every codebase I've worked on that uses fetch() directly ends up with the same file. It's usually called http.ts or apiClient.ts, and it grows in the same order:

  1. A base URL, because nobody wants to concatenate strings at every call site.
  2. JSON.stringify on the way out, res.json() on the way back.
  3. if (!res.ok) throw new Error(res.statusText), which quietly throws away the error body the server sent you.
  4. An AbortController and a setTimeout, because fetch has no timeout.
  5. A retry loop, written at 2am during an incident, that retries POST /orders.

fetch() is the right primitive. It's just the wrong ergonomics. So I wrote that wrapper one last time, tested it properly, and published it as Celero (from Latin celer, "swift").

npm install celero 
import { createClient } from "celero"; const api = createClient({ baseURL: "https://api.example.com", timeout: 10_000, retry: { attempts: 3 }, }); const { data } = await api.get<User>("/users/123"); 

It has zero runtime dependencies and runs anywhere fetch does: Node 18+, Bun, Deno, browsers, Cloudflare Workers and React Native. Here's what it does that the hand-rolled version usually gets wrong.

1. Errors that keep the body

With raw fetch, a 404 resolves. You check res.ok, and by the time you throw, the server's helpful { "message": "User not found" } is usually gone.

Celero throws on non-2xx, and the parsed error body travels with the error:

import { isHttpError } from "celero"; try { await api.get<User>("/users/999"); } catch (error) { if (isHttpError<{ message: string }>(error)) { error.status; // 404 error.response.data.message; // "User not found" error.request.url; // the URL that failed } } 

Every failure mode gets its own class with a stable code: HttpError, TimeoutError, NetworkError, CanceledError, ParseError, ConfigError and CircuitOpenError. All of them extend CeleroError, so one catch tells "the request failed" apart from "my code has a bug":

import { isCeleroError, ErrorCode } from "celero"; try { await api.get("/users"); } catch (error) { if (!isCeleroError(error)) throw error; // a real bug: let it surface switch (error.code) { case ErrorCode.Timeout: return showRetryBanner(); case ErrorCode.Network: return showOfflineState(); case ErrorCode.HttpStatus: return showServerMessage(error); } } 

No more TypeError: fetch failed for everything from DNS to CORS.

2. Retries that won't charge a customer twice

Retrying is easy. Retrying safely is the part everyone skips.

const api = createClient({ retry: { attempts: 3 } }); 

By default, that only retries:

  • Idempotent methods: GET, HEAD, OPTIONS, PUT, DELETE. POST and PATCH are excluded, because replaying them can create a second order. You can opt in per endpoint when you know it's safe.
  • Transient statuses: 408, 425, 429, 500, 502, 503, 504.
  • Transport failures: a NetworkError. A CanceledError is never retried.

Backoff is exponential with full jitter, which is on by default. Clients retrying on identical schedules are what turn a two-second blip into a thundering herd. A Retry-After header, in seconds or as an HTTP date, overrides the computed delay, so a 429 gets respected instead of hammered.

3. A circuit breaker, because retries make outages worse

Here's the uncomfortable thing about retries: when a service is actually down, every client multiplying its load by four is the opposite of helpful.

const api = createClient({ baseURL: "https://api.example.com", retry: { attempts: 3 }, breaker: true, }); 

After enough consecutive failures, the circuit opens and requests fail fast with CircuitOpenError, without touching the network. After a cooldown it lets one probe through, and closes again if that succeeds. Circuits are keyed per origin, so one sick host never trips requests to a healthy one. And a 4xx doesn't count as a failure: that's your request being wrong, not the server being unhealthy.

import { isCircuitOpenError } from "celero"; try { return await api.get("/recommendations"); } catch (error) { if (isCircuitOpenError(error)) return cachedRecommendations(); // degrade gracefully throw error; } 

4. as User is a lie. schema is a guarantee.

api.get<User>() is a type assertion. Your API can return anything it likes, and TypeScript will believe you. Celero accepts any Standard Schema (Zod, Valibot or ArkType), validates the response, and infers the type from the schema:

import { z } from "zod"; const User = z.object({ id: z.number(), name: z.string(), email: z.email() }); const { data } = await api.get("/users/1", { schema: User }); // ^? { id: number; name: string; email: string } 

A mismatch throws a ParseError that names the field:

ParseError: Response from https://api.example.com/users/1 failed schema validation — id: Invalid input: expected number, received string 

Celero doesn't depend on any schema library. The Standard Schema interface is declared structurally, which is how the package stays at zero dependencies.

5. Streaming LLM responses without writing an SSE parser

If you've integrated an LLM API, you've probably hand-rolled a Server-Sent Events parser, and probably got the edge cases wrong: events split across network chunks, multi-line data: fields, multi-byte characters split mid-rune.

const { data: events } = await api.sse("/chat/completions", { method: "POST", body: { model: "...", stream: true }, }); for await (const event of events) { if (event.data === "[DONE]") break; process.stdout.write(JSON.parse(event.data).delta); } 

The parser follows the WHATWG event-stream rules. NDJSON gets the same treatment, and with a schema, each row is validated as it arrives, so a bad row fails at that row, not at the end of a 2 GB export:

const { data: rows } = await api.ndjson("/logs/export", { schema: LogLine }); for await (const row of rows) console.log(row.level, row.message); 

6. Caching that speaks HTTP

There's an opt-in response cache that understands what servers actually send:

const api = createClient({ baseURL: "https://api.example.com", responseCache: { ttl: 30_000, // fresh for 30s staleWhileRevalidate: 300_000, // then serve stale while refreshing }, }); const { data, cached } = await api.get("/config"); 

It reads Cache-Control (max-age, no-store, no-cache, stale-while-revalidate). When an entry expires but has an ETag or Last-Modified, the next request is conditional, so an unchanged resource costs a 304 instead of the whole body.

The cache key includes Authorization by default. Two users sharing a client never share a cached response. That's a data leak, not a performance trade-off, so it isn't something you have to remember to configure.

7. Deduplication that survives an unmounting component

const api = createClient({ dedup: true }); // One network request, three callers. await Promise.all([api.get("/me"), api.get("/me"), api.get("/me")]); 

The subtle part is cancellation. Callers are reference-counted: if one caller aborts, only that caller rejects, and the shared request is cancelled only once every caller has given up. Without that, one component unmounting would cancel a request its siblings are still waiting on, which is a bug I've seen ship more than once.

8. Things you'd otherwise find on Stack Overflow

  • Upload progress with fetch. The Fetch standard has no upload progress event. Celero sends the body as a ReadableStream and counts bytes as the transport pulls them, which gives a real measure, not a guess. It keeps Content-Length when the size is known (S3 presigned uploads need it), and retries still work. Download progress works everywhere; upload progress needs request streaming, so Node, Deno, Bun, Workers and Chromium, not Safari or Firefox.
  • Interceptors, with the API you already know from axios: api.interceptors.request.use(...). The recipes doc has a token-refresh pattern that refreshes once, even when ten requests get a 401 at the same moment.
  • client.extend(), which derives a client with extra defaults (an admin API, a different timeout) without the child ever mutating its parent.
  • A default export for one-off calls: import celero from "celero"; await celero.get(url).

9. And if you want it: a query layer and React hooks

The core is a transport. It doesn't try to be your data layer. But two optional entry points ship alongside it, and you pay nothing unless you import them.

celero/query is a framework-agnostic data layer with caching, background refetch (on mount, focus, reconnect and interval), prefix invalidation, optimistic updates with exact rollback, infinite queries, offline persistence and cross-tab sync:

import { queryOptions } from "celero/query"; export const userQuery = (id: string) => queryOptions({ queryKey: ["users", id], queryFn: ({ signal }) => api.get(`/users/${id}`, { signal }).then((r) => r.data), staleTime: 30_000, }); 

celero/react puts hooks on top of it, all built on useSyncExternalStore. That means they're correct under concurrent rendering and don't double-fetch in StrictMode. No provider required.

import { useQuery, useSuspenseQuery } from "celero/react"; function User({ id }: { id: string }) { const { data, isPending, error } = useQuery(userQuery(id)); if (isPending) return <Spinner />; if (error) return <ErrorMessage error={error} />; return <h1>{data.name}</h1>; } // Or let Suspense handle loading: `data` is typed `User`, never `undefined`. function UserCard({ id }: { id: string }) { const { data } = useSuspenseQuery(userQuery(id)); return <h1>{data.name}</h1>; } 

useSuspenseQuery and networkMode: "offlineFirst" (one attempt even while offline, so a service worker can answer it, then retries that wait for the network instead of failing) are new in 0.3.

What it deliberately is not

I'd rather you pick the right tool than pick this one:

  • Not a mocking framework. Pass your own fetch in tests; that's the whole story.
  • Not a replacement for TanStack Query if you're already happy with it. The transport cache answers "have I fetched this URL recently?". A data layer answers "what does the UI know, and who's watching it?". Celero's transport is happy to sit underneath any data layer.
  • The default cache is per-process memory. Bring your own CacheStore to share it across servers.
  • Mutations don't invalidate the transport cache automatically. Call api.cache.invalidate() after a write. Explicit beats magic here.

How it's built

A few things I cared about, if you like reading other people's design decisions:

  • Documentation is tested. The core recipes (auth refresh, cancellation and more) run as part of the test suite, because docs that never run rot silently. The suite is at 380 tests and counting.
  • Standards over invention. Revalidation follows RFC 9111 (a 304 refreshes the stored headers, so a new max-age or rotated ETag takes effect). SSE parsing follows the WHATWG spec. Validation uses Standard Schema rather than picking a winner.
  • Timeouts and cancellation are different errors. Celero owns its abort controller rather than using AbortSignal.timeout, because "the user cancelled" and "we timed out" need different handling. Only one of them should ever be retried.
  • Timers never hold your process open. Retry backoffs and timeouts are unref'd in Node, so a script finishes when its work does.

Try it

npm install celero 

It's young, so issues and bug reports are the most useful thing you can send me. And I'm curious: what's in your apiClient.ts that I haven't covered? Tell me in the comments.