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

The createFetch function allows you to create customized instances of ofetch with predefined defaults and global options.

Type Signature

export function createFetch(globalOptions?: CreateFetchOptions): $Fetch

Usage

import { createFetch } from 'ofetch'

const apiFetch = createFetch({
  defaults: {
    baseURL: 'https://api.example.com',
    headers: {
      Authorization: 'Bearer token'
    }
  },
  fetch: customFetch
})

const users = await apiFetch('/users')

Parameters

globalOptions
CreateFetchOptions
Global configuration for the fetch instance
return
$Fetch
A new ofetch instance. See ofetch.

CreateFetchOptions

export interface CreateFetchOptions {
  defaults?: FetchOptions;
  fetch?: Fetch;
}

defaults

defaults
FetchOptions
Default FetchOptions to apply to all requests made with this instance. These can be overridden on a per-request basis.
const apiFetch = createFetch({
  defaults: {
    baseURL: 'https://api.example.com',
    headers: {
      'Content-Type': 'application/json'
    },
    retry: 3,
    timeout: 10000
  }
})

fetch

fetch
Fetch
Custom fetch implementation to use instead of globalThis.fetch. Useful for providing polyfills or custom fetch behavior.
import { fetch } from 'undici'

const customFetch = createFetch({
  fetch: fetch as typeof globalThis.fetch
})

Examples

API Client with Authentication

const authenticatedFetch = createFetch({
  defaults: {
    baseURL: 'https://api.example.com',
    headers: {
      Authorization: `Bearer ${token}`
    },
    onRequest({ options }) {
      console.log('Making request:', options)
    },
    onResponseError({ response }) {
      console.error('Request failed:', response.status)
    }
  }
})

Custom Retry Configuration

const resilientFetch = createFetch({
  defaults: {
    retry: 5,
    retryDelay: 500,
    retryStatusCodes: [408, 409, 425, 429, 500, 502, 503, 504],
    timeout: 30000
  }
})

Node.js with Custom Fetch

import { fetch } from 'node-fetch-native'

const nodeFetch = createFetch({
  fetch: fetch as typeof globalThis.fetch,
  defaults: {
    baseURL: 'http://localhost:3000'
  }
})

Build docs developers (and LLMs) love