SwoffSwoff

fetchWithCache

Unified fetch with caching, auth, offline queue, auto-invalidation.

fetchWithCache<T>(input, options?)

From swoff/fetch/core.ts.

ParamTypeDescription
inputRequestInfoURL string or Request object
optionsFetchWithCacheOptionsSee below

Returns: Promise<{ response: Response & { json(): Promise<T> }, fromCache: boolean }>

All RequestInit fields are supported (method, body, headers, credentials, signal, etc.) plus:

OptionTypeDefaultDescription
tagsstring[]auto-generated from URLCache invalidation tags for this request
authbooleanfalseAttach auth token via withAuthHeaders()
queueOfflinebooleantrueWhen offline, queue writes to IndexedDB
invalidate'auto' | string[] | false'auto'Auto-invalidate cache tags after successful mutation
type'read' | 'mutation'auto-detectedOverride read/mutation detection
strategy'cache-first' | 'network-first' | 'stale-while-revalidate' | 'cache-only' | 'network-only' | 'reactive'Override caching strategy per-request (highest priority)
staleTimenumberOverride stale time in seconds (reactive-only)
validateSuccess(response: Response) => boolean | Promise<boolean>res.okCustom mutation success check (e.g. when API returns 200 with { success: false })
invalidateUrlstringthe request URLOverride the URL used for auto-invalidation tags. Useful when mutation URL differs from cache tag URL.
signalAbortSignalAbortController signal for cancellation

Behavior:

  • Read vs mutation: GET/HEAD → read (cached). POST/PUT/DELETE/PATCH → mutation (pass through). Override with type: 'read' or type: 'mutation'.
  • Offline reads: returns cached response if available; throws if not cached. Abort check: if signal.aborted, throws AbortError before cache lookup.
  • Offline writes: queues to IndexedDB (when mutationQueue enabled). Replays on online event. Disable per-request with queueOffline: false.
  • Request batching + dedup: concurrent GETs to the same URL within a 50 ms window coalesce into one network request. After the batch window closes, in-flight requests are deduplicated (late arrivals piggyback on the active promise). Each caller receives a cloned response.
  • Auto-tags: when tagInvalidation enabled, tags derived from URL path for read requests.
  • Auto-invalidate: after a successful mutation, matching cache tags are invalidated. Mutation success is determined by response.ok by default, or validateSuccess if provided. The auto-invalidation target URL can be overridden with invalidateUrl.
  • Auth: when auth: true, attaches auth headers. Dispatches sw-auth-unauthorized on 401.
  • StaleTime: 3-tier resolution (per-request / route pattern / global default). Only affects reactive strategy.
  • Background refresh retry: failed refetches are retried with exponential backoff via a shared RetryConfig.

On this page