Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/unjs/ofetch/llms.txt

Use this file to discover all available pages before exploring further.

Overview

ofetch is the main function exported by the library. It provides a modern, type-safe interface for making HTTP requests with automatic response parsing, error handling, and retry logic. The $fetch alias is also available and functionally identical to ofetch.

Type Signature

export interface $Fetch {
  <T = any, R extends ResponseType = "json">(
    request: FetchRequest,
    options?: FetchOptions<R>
  ): Promise<MappedResponseType<R, T>>;
  raw<T = any, R extends ResponseType = "json">(
    request: FetchRequest,
    options?: FetchOptions<R>
  ): Promise<FetchResponse<MappedResponseType<R, T>>>;
  native: Fetch;
  create(defaults: FetchOptions, globalOptions?: CreateFetchOptions): $Fetch;
}

Usage

Basic Request

request
FetchRequest
required
The URL or Request object to fetch
options
FetchOptions<R>
Request options and configuration. See FetchOptions for details.
return
Promise<MappedResponseType<R, T>>
Returns a promise that resolves to the parsed response data based on the responseType
const data = await ofetch('/api/users')

Methods

ofetch()

The main function that returns parsed response data.
const users = await ofetch<User[]>('/api/users')
request
FetchRequest
required
URL string or Request object
options
FetchOptions<R>
Request configuration options
return
Promise<MappedResponseType<R, T>>
Parsed response data (JSON by default)

ofetch.raw()

Returns the full Response object with parsed data available in _data property.
const response = await ofetch.raw('/api/users')
console.log(response.status) // 200
console.log(response._data) // parsed data
request
FetchRequest
required
URL string or Request object
options
FetchOptions<R>
Request configuration options
return
Promise<FetchResponse<MappedResponseType<R, T>>>
Full Response object with _data property containing parsed response. See FetchResponse.

ofetch.native()

Access to the native fetch function used internally.
const response = await ofetch.native('/api/users')
...args
Parameters<typeof globalThis.fetch>
Standard fetch API arguments
return
Promise<Response>
Native fetch Response object

ofetch.create()

Create a new ofetch instance with custom default options.
const apiFetch = ofetch.create({
  baseURL: 'https://api.example.com',
  headers: {
    Authorization: 'Bearer token'
  }
})

const users = await apiFetch('/users')
defaults
FetchOptions
required
Default options to apply to all requests made with this instance. See FetchOptions.
globalOptions
CreateFetchOptions
Global configuration options. See createFetch.
return
$Fetch
A new ofetch instance with the provided defaults

Type Parameters

T
any
default:"any"
The expected type of the response data
R
ResponseType
default:"json"
The response type: "json", "text", "blob", "arrayBuffer", or "stream". See ResponseType.