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.
ofetch makes it easy to add custom headers to your requests using the headers option.
Basic Usage
Object notation
Headers instance
Array notation
import { ofetch } from 'ofetch'
await ofetch ( '/api/users' , {
headers: {
'Authorization' : 'Bearer token123' ,
'X-Custom-Header' : 'value'
}
})
When sending JSON bodies, ofetch automatically sets headers for you:
await ofetch ( '/api/users' , {
method: 'POST' ,
body: { name: 'John' }
})
// Automatically adds:
// content-type: application/json
// accept: application/json
You can override these defaults:
await ofetch ( '/api/users' , {
method: 'POST' ,
body: { name: 'John' },
headers: {
'content-type' : 'application/vnd.api+json'
}
})
Headers are merged when using $fetch.create() or when passing a Request object:
const api = ofetch . create ({
headers: {
'Authorization' : 'Bearer token123' ,
'X-API-Version' : '1.0'
}
})
// These headers are merged with the defaults
await api ( '/users' , {
headers: {
'X-Custom-Header' : 'value' ,
'X-API-Version' : '2.0' // Overrides default
}
})
// Final headers:
// Authorization: Bearer token123
// X-API-Version: 2.0
// X-Custom-Header: value
Headers from Request objects are preserved and can be overridden:
const req = new Request ( 'https://api.example.com/users' , {
headers: { 'foo' : '1' }
})
await ofetch ( req , {
headers: {
'foo' : '2' , // Overrides Request header
'bar' : '3' // Added to Request headers
}
})
// Final headers: foo: 2, bar: 3
Common Patterns
Authentication
const api = ofetch . create ({
baseURL: 'https://api.example.com' ,
headers: {
'Authorization' : `Bearer ${ getToken () } `
}
})
API Versioning
await ofetch ( '/api/users' , {
headers: {
'Accept' : 'application/vnd.myapi.v2+json'
}
})
Custom User Agent
await ofetch ( 'https://api.example.com/data' , {
headers: {
'User-Agent' : 'MyApp/1.0'
}
})
Content Negotiation
await ofetch ( '/api/report' , {
headers: {
'Accept' : 'application/pdf'
},
responseType: 'blob'
})
Type Definition
Headers inherit from the standard RequestInit interface and support all native header formats:
Where HeadersInit can be:
Headers instance
Record<string, string>
[string, string][]
Implementation Details
Headers are internally converted to a Headers instance and merged using the mergeHeaders function from src/utils.ts:121-138. Default headers are set at src/fetch.ts:144-153 for JSON-serializable bodies.