HTTP client with interceptors, timeout, retry, cache, deduplication, and download progress.

Basic usage

const api = new Request('https://api.example.com')

// Directly awaitable
const user = await api.get<User>('/users/1')

// Lifecycle callbacks
await api.get('/users', {
onSuccess: setUsers,
onError: toast.error,
onFinally: () => setLoading(false),
})

Composable best practice

Prefer small focused instances over one instance with all interceptors:

// ── Building blocks (pure functions, reusable) ──
const addAuth: RequestInterceptor = (config) => ({
...config,
headers: { ...config.headers, Authorization: `Bearer ${getToken()}` }
})
const addLang: RequestInterceptor = (config) => ({
...config,
headers: { ...config.headers, 'Accept-Language': 'zh-CN' }
})

// ── Compose: each instance handles one concern ──
const authApi = new Request('https://api.example.com')
authApi.useRequestInterceptor(addAuth)
authApi.useRequestInterceptor(addLang)

const publicApi = new Request('https://open.api.com')

// ── Or use per-request interceptors ──
api.get('/users', {}, {
requestInterceptors: [addAuth],
onSuccess: setUsers,
})

Constructors

Properties

baseUrl: string = ''
cacheMap: Map<string, CacheEntry> = ...
errorInterceptors: ErrorInterceptor[] = []
inflightMap: Map<string, Promise<unknown>> = ...
requestInterceptors: RequestInterceptor[] = []
responseInterceptors: ResponseInterceptor<any, any>[] = []

Methods

  • Parameters

    • data: unknown

    Returns string | Blob | FormData | URLSearchParams

  • Parameters

    • method: string
    • url: string

    Returns string

  • Parameters

    • method: string
    • data: unknown
    • config: RequestInit
    • controller: AbortController

    Returns RequestInit

  • Parameters

    • url: string
    • method: string
    • Optional params: Record<PropertyKey, any>

    Returns string

  • Clear the in-memory response cache.

    Returns void

  • Type Parameters

    • T

    Parameters

    Returns Promise<T>

  • Type Parameters

    • T

    Parameters

    • requestUrl: string
    • method: string
    • data: unknown
    • requestConfig: RequestInit
    • controller: AbortController
    • requestInterceptors: RequestInterceptor[]
    • responseInterceptors: ResponseInterceptor<any, any>[]
    • errorInterceptors: ErrorInterceptor[]
    • onDownloadProgress: undefined | ((loaded, total) => void)
    • timeout: undefined | number
    • maxRetries: number
    • retryDelayMs: number
    • cache: undefined | boolean | CacheConfig
    • cacheKey: string

    Returns Promise<T>

  • Parameters

    • url: string

    Returns boolean

  • Parameters

    • baseUrl: string
    • url: string

    Returns string

  • Parameters

    • Optional headers: HeadersInit

    Returns Record<string, string>

  • Parameters

    • response: Response

    Returns Promise<any>

  • Parameters

    • response: Response
    • callbacks: SSECallbacks
    • controller: AbortController

    Returns void

  • Parameters

    • response: Response
    • onProgress: ((loaded, total) => void)
        • (loaded, total): void
        • Parameters

          • loaded: number
          • total: number

          Returns void

    Returns Promise<unknown>

  • Type Parameters

    • T

    Parameters

    • interceptors: T[]
    • interceptor: T

    Returns void

  • Parameters

    Returns Promise<RequestInit>

  • Create an SSE (Server-Sent Events) connection.

    Uses Fetch API under the hood, so it supports:

    • Custom headers (unlike native EventSource)
    • POST requests
    • All HTTP methods

    Type Parameters

    • T = unknown

    Parameters

    Returns RequestHandle<T>

    Example

    const api = new Request('https://api.example.com')

    // GET SSE (default)
    const handle = api.sse('/events', {
    onMessage: (event) => console.log(event.data),
    onError: (err) => console.error(err),
    })

    // POST SSE with data
    const handle = api.sse('/chat/completions', {
    method: 'POST',
    data: { prompt: 'Hello' },
    onMessage: (event) => {
    const parsed = JSON.parse(event.data)
    console.log(parsed)
    },
    })

    // Cancel the connection
    handle.abort()
    ```n
  • Type Parameters

    • T = unknown
    • U = unknown

    Parameters

    Returns (() => void)

      • (): void
      • Returns void