Skip to content

fetchJson

Fetches a URL and returns its parsed JSON body, retrying transient failures.

Retried: network errors, 5xx and 429 responses. Not retried, and thrown at once: other 4xx responses, a body that is not valid JSON (a SyntaxError) and an aborted request. After the last attempt, the last error is thrown: an HttpError (with status and url) for a bad status, or whatever fetch rejected with.

Pass a URL or a string: a Request with a body cannot be sent twice, so it can’t be retried.

init.signal cancels the whole call: the running request, and the wait before the next one.

Available since v3.1.11

import { fetchJson } from '@helpers4/fetch';
// or, from the all-in-one package (same code, one install):
import { fetchJson } from 'helpers4/fetch';
fetchJson<T>(input: RequestInfo | URL, init?: RequestInit, options: FetchJsonOptions): Promise<T>
ParameterTypeDescription
inputRequestInfo | URLURL or `Request` object passed to `fetch`
initRequestInitOptional `RequestInit` options passed to `fetch` (optional)
optionsFetchJsonOptionsRetry configuration — see FetchJsonOptions

Promise<T> — The parsed JSON body

A 503 is retried; once the server answers, the parsed body is returned.

// the server answers 503, then 200 with { "stars": 42 }
await fetchJson<{ stars: number }>('https://api.example.com/repo', undefined, { retry: { delayMs: 0 } })
// => { stars: 42 }

Client errors fail at once with an HttpError carrying the status.

await fetchJson('https://api.example.com/missing')
// throws HttpError { status: 404 } after a single request

Options for fetchJson.

interface FetchJsonOptions {
  retry?: RetryOptions;
}

View source on GitHub