Efe

Efe

SOULTEL

Full-Stack Developer & Open Source Enthusiast

Back to Snippets
TYPESCRIPTJanuary 15, 2024
TypeScript

fetchAPI Wrapper

Type-safe fetch with error handling

TypeScriptHTTPAPIError Handling

TYPESCRIPT
export async function fetchAPI(
  url: string,
  options?: RequestInit
): Promise {
  const response = await fetch(url, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...options?.headers,
    },
  })

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`)
  }

  return response.json()
}

Usage

TYPESCRIPT
// Basic usage
const users = await fetchAPI('/api/users')

// With auth
const data = await fetchAPI('/api/protected', {
  headers: { 'Authorization': 'Bearer token' }
})