0
# Core Fetch Operations
1
2
Primary fetch functionality with enhanced features including automatic JSON parsing, intelligent error handling, cross-environment compatibility, and response type management.
3
4
## Capabilities
5
6
### Main Fetch Function
7
8
The primary ofetch function that provides enhanced fetch capabilities with automatic response parsing and error handling.
9
10
```typescript { .api }
11
/**
12
* Enhanced fetch function with automatic response parsing
13
* @param request - URL string or Request object
14
* @param options - Fetch configuration options
15
* @returns Promise resolving to parsed response data
16
*/
17
function ofetch<T = any, R extends ResponseType = "json">(
18
request: FetchRequest,
19
options?: FetchOptions<R>
20
): Promise<MappedResponseType<R, T>>;
21
22
// Alias for ofetch
23
const $fetch: typeof ofetch;
24
```
25
26
**Usage Examples:**
27
28
```typescript
29
import { ofetch } from "ofetch";
30
31
// Simple GET request with automatic JSON parsing
32
const users = await ofetch("https://api.example.com/users");
33
34
// GET with query parameters
35
const filtered = await ofetch("https://api.example.com/users", {
36
query: { active: true, limit: 10 }
37
});
38
39
// POST with JSON body
40
const newUser = await ofetch("https://api.example.com/users", {
41
method: "POST",
42
body: { name: "Alice", email: "alice@example.com" }
43
});
44
45
// Custom response type
46
const imageBlob = await ofetch("https://api.example.com/image.png", {
47
responseType: "blob"
48
});
49
50
// With type safety
51
interface User {
52
id: number;
53
name: string;
54
email: string;
55
}
56
const user = await ofetch<User>("https://api.example.com/users/1");
57
```
58
59
### Raw Response Access
60
61
Access the full Response object with parsed data attached, useful for accessing headers, status codes, and other response metadata.
62
63
```typescript { .api }
64
/**
65
* Fetch with access to full Response object
66
* @param request - URL string or Request object
67
* @param options - Fetch configuration options
68
* @returns Promise resolving to Response object with _data property
69
*/
70
function raw<T = any, R extends ResponseType = "json">(
71
request: FetchRequest,
72
options?: FetchOptions<R>
73
): Promise<FetchResponse<MappedResponseType<R, T>>>;
74
```
75
76
**Usage Examples:**
77
78
```typescript
79
import { ofetch } from "ofetch";
80
81
// Access response headers and status
82
const response = await ofetch.raw("https://api.example.com/users");
83
console.log(response.status); // 200
84
console.log(response.headers.get("content-type"));
85
console.log(response._data); // Parsed response data
86
87
// Handle different status codes
88
const response = await ofetch.raw("https://api.example.com/users/999", {
89
ignoreResponseError: true
90
});
91
92
if (response.status === 404) {
93
console.log("User not found");
94
} else {
95
console.log(response._data);
96
}
97
```
98
99
### Native Fetch Access
100
101
Direct access to the underlying native fetch API for cases requiring standard fetch behavior.
102
103
```typescript { .api }
104
/**
105
* Access to native fetch API
106
* @param args - Standard fetch arguments
107
* @returns Promise resolving to standard Response object
108
*/
109
native(...args: Parameters<typeof globalThis.fetch>): Promise<Response>;
110
```
111
112
**Usage Examples:**
113
114
```typescript
115
import { ofetch } from "ofetch";
116
117
// Use native fetch for streaming or custom handling
118
const response = await ofetch.native("https://api.example.com/stream");
119
const reader = response.body?.getReader();
120
121
// Standard fetch behavior without ofetch enhancements
122
const response = await ofetch.native("https://api.example.com/data", {
123
method: "POST",
124
body: JSON.stringify({ key: "value" }),
125
headers: { "Content-Type": "application/json" }
126
});
127
const data = await response.json();
128
```
129
130
### Instance Creation
131
132
Create customized fetch instances with default options, base URLs, and configuration that applies to all requests made with that instance.
133
134
```typescript { .api }
135
/**
136
* Create a customized fetch instance with default options
137
* @param defaults - Default options to apply to all requests
138
* @param globalOptions - Global configuration for the instance
139
* @returns New $Fetch instance with applied defaults
140
*/
141
function create(
142
defaults?: FetchOptions,
143
globalOptions?: CreateFetchOptions
144
): $Fetch;
145
```
146
147
**Usage Examples:**
148
149
```typescript
150
import { ofetch } from "ofetch";
151
152
// Create API client with base URL and auth
153
const api = ofetch.create({
154
baseURL: "https://api.example.com",
155
headers: {
156
"Authorization": "Bearer token123",
157
"Content-Type": "application/json"
158
},
159
timeout: 5000
160
});
161
162
// Use the configured instance
163
const users = await api("/users"); // GET https://api.example.com/users
164
const user = await api("/users/1"); // GET https://api.example.com/users/1
165
166
// Override defaults per request
167
const adminUsers = await api("/admin/users", {
168
headers: { "X-Admin": "true" }
169
});
170
171
// Create instance with custom fetch implementation
172
const customFetch = ofetch.create({
173
baseURL: "https://internal.api.com"
174
}, {
175
fetch: globalThis.fetch,
176
Headers: globalThis.Headers
177
});
178
```
179
180
### Response Type Handling
181
182
Configure how responses are parsed based on content type or explicit specification.
183
184
```typescript { .api }
185
type ResponseType = "json" | "text" | "blob" | "arrayBuffer" | "stream";
186
187
type MappedResponseType<R extends ResponseType, JsonType = any> =
188
R extends keyof ResponseMap ? ResponseMap[R] : JsonType;
189
190
interface ResponseMap {
191
blob: Blob;
192
text: string;
193
arrayBuffer: ArrayBuffer;
194
stream: ReadableStream<Uint8Array>;
195
}
196
```
197
198
**Usage Examples:**
199
200
```typescript
201
import { ofetch } from "ofetch";
202
203
// Automatic JSON parsing (default)
204
const data = await ofetch("https://api.example.com/data.json");
205
206
// Force text parsing
207
const text = await ofetch("https://api.example.com/document", {
208
responseType: "text"
209
});
210
211
// Get binary data as blob
212
const image = await ofetch("https://api.example.com/image.png", {
213
responseType: "blob"
214
});
215
216
// Get raw bytes as ArrayBuffer
217
const buffer = await ofetch("https://api.example.com/file.bin", {
218
responseType: "arrayBuffer"
219
});
220
221
// Get streaming response
222
const stream = await ofetch("https://api.example.com/large-file", {
223
responseType: "stream"
224
});
225
226
// Custom response parser
227
const data = await ofetch("https://api.example.com/custom", {
228
parseResponse: (text) => text.split("\\n").map(line => line.trim())
229
});
230
```
231
232
## Global Exports
233
234
```typescript { .api }
235
// Universal exports (from "ofetch")
236
// Automatically uses Node.js optimizations when in Node.js environment
237
export const ofetch: $Fetch;
238
export const $fetch: $Fetch;
239
export const fetch: typeof globalThis.fetch;
240
export const Headers: typeof globalThis.Headers;
241
export const AbortController: typeof globalThis.AbortController;
242
export function createFetch(globalOptions?: CreateFetchOptions): $Fetch;
243
export class FetchError<T = any> extends Error implements IFetchError<T> {}
244
export function createFetchError<T = any>(ctx: FetchContext<T>): IFetchError<T>;
245
246
// Node.js specific exports (from "ofetch/node")
247
// Same API as main export, but with explicit Node.js optimizations
248
export const ofetch: $Fetch;
249
export const $fetch: $Fetch;
250
export const fetch: typeof globalThis.fetch; // With conditional keep-alive support
251
export const Headers: typeof globalThis.Headers;
252
export const AbortController: typeof globalThis.AbortController;
253
export function createFetch(globalOptions?: CreateFetchOptions): $Fetch;
254
export function createNodeFetch(): typeof globalThis.fetch;
255
export class FetchError<T = any> extends Error implements IFetchError<T> {}
256
export function createFetchError<T = any>(ctx: FetchContext<T>): IFetchError<T>;
257
258
// Utilities (from "ofetch")
259
export function isPayloadMethod(method?: string): boolean;
260
export function isJSONSerializable(value: any): boolean;
261
export function detectResponseType(contentType?: string): ResponseType;
262
export function resolveFetchOptions<R extends ResponseType, T>(
263
request: FetchRequest,
264
input: FetchOptions<R, T> | undefined,
265
defaults: FetchOptions<R, T> | undefined,
266
Headers: typeof globalThis.Headers
267
): ResolvedFetchOptions<R, T>;
268
export function callHooks<C extends FetchContext>(
269
context: C,
270
hooks: FetchHook<C> | FetchHook<C>[] | undefined
271
): Promise<void>;
272
```