0
# Core Fetch Operations
1
2
The primary fetch function that provides an enhanced, drop-in replacement for the standard Fetch API with additional enterprise features.
3
4
## Capabilities
5
6
### Main Fetch Function
7
8
The core fetch function implements the standard Fetch API with additional make-fetch-happen features.
9
10
```javascript { .api }
11
/**
12
* Enhanced fetch function with caching, retries, and proxy support
13
* @param {string|Request} url - URL string or Request object to fetch
14
* @param {FetchOptions} [options] - Request options with make-fetch-happen extensions
15
* @returns {Promise<Response>} Promise resolving to Response object
16
*/
17
function fetch(url, options);
18
```
19
20
**Usage Examples:**
21
22
```javascript
23
const fetch = require('make-fetch-happen');
24
25
// Basic GET request
26
const response = await fetch('https://api.example.com/users');
27
const users = await response.json();
28
29
// POST request with body
30
const response = await fetch('https://api.example.com/users', {
31
method: 'POST',
32
headers: { 'Content-Type': 'application/json' },
33
body: JSON.stringify({ name: 'Alice', email: 'alice@example.com' })
34
});
35
36
// Request with all enhanced features
37
const response = await fetch('https://api.example.com/data', {
38
// Caching
39
cachePath: './my-cache',
40
cache: 'default',
41
42
// Retries
43
retry: { retries: 3, factor: 2 },
44
onRetry: (cause) => console.log('Retrying due to:', cause.message),
45
46
// Security
47
integrity: 'sha256-abcd1234...',
48
strictSSL: true,
49
50
// Network
51
proxy: 'http://proxy.company.com:8080',
52
timeout: 30000
53
});
54
```
55
56
### Request Object
57
58
Standard Request constructor re-exported from minipass-fetch.
59
60
```javascript { .api }
61
/**
62
* HTTP request representation
63
* @param {string|Request} input - URL or existing Request
64
* @param {RequestInit} [init] - Request initialization options
65
*/
66
class Request {
67
constructor(input, init);
68
69
readonly url: string;
70
readonly method: string;
71
readonly headers: Headers;
72
body: any;
73
readonly redirect: string;
74
readonly referrer: string;
75
readonly referrerPolicy: string;
76
readonly mode: string;
77
readonly credentials: string;
78
readonly cache: string;
79
readonly integrity: string;
80
readonly keepalive: boolean;
81
readonly signal: AbortSignal;
82
83
clone(): Request;
84
arrayBuffer(): Promise<ArrayBuffer>;
85
blob(): Promise<Blob>;
86
json(): Promise<any>;
87
text(): Promise<string>;
88
}
89
```
90
91
### Response Object
92
93
Standard Response constructor re-exported from minipass-fetch.
94
95
```javascript { .api }
96
/**
97
* HTTP response representation
98
* @param {any} [body] - Response body
99
* @param {ResponseInit} [init] - Response initialization options
100
*/
101
class Response {
102
constructor(body, init);
103
104
readonly ok: boolean;
105
readonly status: number;
106
readonly statusText: string;
107
readonly headers: Headers;
108
readonly url: string;
109
readonly redirected: boolean;
110
readonly type: string;
111
body: ReadableStream;
112
readonly bodyUsed: boolean;
113
114
clone(): Response;
115
arrayBuffer(): Promise<ArrayBuffer>;
116
blob(): Promise<Blob>;
117
buffer(): Promise<Buffer>;
118
json(): Promise<any>;
119
text(): Promise<string>;
120
121
static error(): Response;
122
static redirect(url: string, status?: number): Response;
123
}
124
```
125
126
### Headers Object
127
128
Standard Headers constructor re-exported from minipass-fetch.
129
130
```javascript { .api }
131
/**
132
* HTTP headers management
133
* @param {HeadersInit} [init] - Initial headers
134
*/
135
class Headers {
136
constructor(init);
137
138
append(name: string, value: string): void;
139
delete(name: string): void;
140
entries(): Iterator<[string, string]>;
141
forEach(callback: (value: string, name: string, headers: Headers) => void): void;
142
get(name: string): string | null;
143
has(name: string): boolean;
144
keys(): Iterator<string>;
145
set(name: string, value: string): void;
146
values(): Iterator<string>;
147
}
148
```
149
150
### FetchError Class
151
152
Error class for fetch-related failures.
153
154
```javascript { .api }
155
/**
156
* Error thrown by fetch operations
157
*/
158
class FetchError extends Error {
159
constructor(message: string, type: string, systemError?: object);
160
161
name: string;
162
message: string;
163
type: string;
164
code?: string;
165
errno?: string;
166
syscall?: string;
167
}
168
```
169
170
**Common error types:**
171
- `'request-timeout'`: Request timed out
172
- `'body-timeout'`: Request body timeout
173
- `'system'`: System-level errors (network, DNS, etc.)
174
- `'no-redirect'`: Redirect not allowed
175
- `'no-location'`: Missing location header in redirect
176
- `'max-redirect'`: Too many redirects
177
178
## Standard Fetch Options
179
180
All standard fetch options are supported:
181
182
```javascript { .api }
183
/**
184
* Standard fetch options (subset of full FetchOptions)
185
*/
186
interface StandardFetchOptions {
187
method?: string; // HTTP method (GET, POST, etc.)
188
headers?: HeadersInit; // Request headers
189
body?: BodyInit; // Request body
190
redirect?: 'follow' | 'manual' | 'error'; // Redirect handling
191
timeout?: number; // Request timeout in milliseconds
192
size?: number; // Maximum response size
193
compress?: boolean; // Enable compression
194
follow?: number; // Maximum redirects to follow
195
}
196
```
197
198
## Automatic Request Headers
199
200
make-fetch-happen automatically sets certain request headers when they are not provided:
201
202
```javascript { .api }
203
/**
204
* Automatically set request headers:
205
* - User-Agent: Set to "${package.name}/${package.version} (+https://npm.im/${package.name})"
206
* - Connection: Set to "keep-alive" if agent is used, "close" otherwise
207
*/
208
```
209
210
**Usage Examples:**
211
212
```javascript
213
// These headers are set automatically
214
const response = await fetch('https://api.example.com/data');
215
// User-Agent: make-fetch-happen/15.0.1 (+https://npm.im/make-fetch-happen)
216
// Connection: keep-alive (or close depending on agent configuration)
217
218
// Override automatic headers
219
const response2 = await fetch('https://api.example.com/data', {
220
headers: {
221
'User-Agent': 'MyApp/1.0',
222
'Connection': 'close'
223
}
224
});
225
```
226
227
## Response Headers
228
229
make-fetch-happen adds special headers to responses:
230
231
### Cache Response Headers
232
233
Added to cached responses (when cachePath is configured):
234
235
- `X-Local-Cache`: Path to the cache directory
236
- `X-Local-Cache-Key`: Unique cache key for this response
237
- `X-Local-Cache-Mode`: Always 'stream'
238
- `X-Local-Cache-Hash`: Integrity hash of cached content
239
- `X-Local-Cache-Status`: Cache status ('miss', 'hit', 'stale', 'revalidated', 'updated', 'skip')
240
- `X-Local-Cache-Time`: Cache insertion timestamp
241
242
### Retry Response Headers
243
244
Added to all responses:
245
246
```javascript { .api }
247
/**
248
* X-Fetch-Attempts header: Number of attempts made for this request
249
* - Starts at 1 for successful first attempt
250
* - Increments with each retry attempt
251
* - Present on all responses regardless of caching configuration
252
*/
253
```
254
255
**Usage Examples:**
256
257
```javascript
258
const response = await fetch('https://flaky-api.example.com/data', {
259
retry: { retries: 3 }
260
});
261
262
// Check how many attempts were made
263
const attempts = response.headers.get('x-fetch-attempts');
264
console.log(`Request completed after ${attempts} attempts`);
265
266
// For successful first attempt: x-fetch-attempts: "1"
267
// For request that succeeded on 3rd try: x-fetch-attempts: "3"
268
```