Skip to content

safeFetch

Wraps fetch with built-in error handling: returns null when the request fails (network error, non-OK status, or parse error) instead of throwing.

Available since v2.0.0

import { safeFetch } from '@helpers4/promise';
safeFetch<T>(input: URL | RequestInfo, init?: RequestInit, options: SafeFetchOptions): Promise<T | null>
ParameterTypeDescription
inputURL | RequestInfoURL or Request object passed to fetch
initRequestInitOptional RequestInit options passed to fetch (optional)
optionsSafeFetchOptionsParsing options (default: { parse: 'json' })

Promise<T | null> — The parsed response body, or null on any failure

Returns null on network error or non-OK status instead of throwing.

const repo = await safeFetch<{ stars: number }>(
  'https://api.github.com/repos/helpers4/typescript'
);
if (repo === null) {
  console.warn('Failed to fetch repo data');
} else {
  console.log(repo.stars);
}

Pass { parse: “text” } to get the raw response body as a string.

const content = await safeFetch<string>(
  'https://example.com/data.txt',
  undefined,
  { parse: 'text' }
);

Options for safeFetch.

interface SafeFetchOptions {
  parse?: "text" | "json";
}

View source on GitHub