0
# Configuration and Defaults
1
2
Create pre-configured fetch functions with default options for consistent behavior across an application.
3
4
## Capabilities
5
6
### Creating Default Fetch Functions
7
8
The `defaults` method creates a new fetch function with pre-configured default options.
9
10
```javascript { .api }
11
/**
12
* Creates a new fetch function with default options
13
* @param {string} [defaultUrl] - Default URL to use if none provided to the fetch call
14
* @param {FetchOptions} [defaultOptions] - Default options to merge with each request
15
* @returns {FetchFunction} New fetch function with defaults applied
16
*/
17
function fetch.defaults(defaultUrl, defaultOptions);
18
19
/**
20
* Alternative signature when only options are provided
21
* @param {FetchOptions} defaultOptions - Default options to apply
22
* @returns {FetchFunction} New fetch function with defaults applied
23
*/
24
function fetch.defaults(defaultOptions);
25
```
26
27
**Usage Examples:**
28
29
```javascript
30
const fetch = require('make-fetch-happen');
31
32
// Create fetch with default cache settings
33
const cachedFetch = fetch.defaults({
34
cachePath: './my-app-cache',
35
cache: 'default',
36
retry: { retries: 2 }
37
});
38
39
// Use the configured fetch
40
const response = await cachedFetch('https://api.example.com/users');
41
42
// Create fetch with default URL and options
43
const apiFetch = fetch.defaults('https://api.example.com', {
44
headers: { 'Authorization': 'Bearer token123' },
45
timeout: 30000
46
});
47
48
// Fetch from the default URL
49
const users = await apiFetch('/users'); // Fetches https://api.example.com/users
50
51
// Override defaults for specific requests
52
const posts = await apiFetch('/posts', {
53
timeout: 60000, // Override default timeout
54
headers: { 'Accept': 'application/json' } // Merge with default headers
55
});
56
```
57
58
### Chaining Defaults
59
60
Default fetch functions also have a `defaults` method, allowing for layered configuration.
61
62
```javascript { .api }
63
/**
64
* Chained defaults method on defaulted fetch functions
65
* @param {string} [defaultUrl] - Additional default URL
66
* @param {FetchOptions} [defaultOptions] - Additional default options
67
* @returns {FetchFunction} New fetch function with layered defaults
68
*/
69
defaultedFetch.defaults(defaultUrl, defaultOptions);
70
```
71
72
**Usage Examples:**
73
74
```javascript
75
// Base configuration for all API calls
76
const baseFetch = fetch.defaults({
77
cachePath: './cache',
78
retry: { retries: 3 }
79
});
80
81
// Specific configuration for authenticated calls
82
const authFetch = baseFetch.defaults({
83
headers: { 'Authorization': 'Bearer token123' }
84
});
85
86
// Specific configuration for admin API
87
const adminFetch = authFetch.defaults('https://admin-api.example.com', {
88
timeout: 60000,
89
headers: { 'X-Admin-Key': 'admin123' }
90
});
91
92
// Each level inherits and extends previous defaults
93
const response = await adminFetch('/users');
94
// URL: https://admin-api.example.com/users
95
// Headers: Authorization, X-Admin-Key
96
// Cache: ./cache
97
// Retry: 3 attempts
98
// Timeout: 60000ms
99
```
100
101
### Option Merging Behavior
102
103
When creating defaulted fetch functions, options are merged according to these rules:
104
105
```javascript { .api }
106
/**
107
* Options merging priority (highest to lowest):
108
* 1. Request-specific options (passed to fetch call)
109
* 2. Layered default options (from chained .defaults() calls)
110
* 3. Base default options (from first .defaults() call)
111
*
112
* Special merging rules:
113
* - Headers are merged (request headers override defaults)
114
* - All other options use simple override behavior
115
*/
116
```
117
118
**Usage Examples:**
119
120
```javascript
121
const defaultFetch = fetch.defaults({
122
headers: {
123
'User-Agent': 'MyApp/1.0',
124
'Accept': 'application/json'
125
},
126
timeout: 30000,
127
retry: { retries: 2 }
128
});
129
130
// Headers are merged, other options override
131
const response = await defaultFetch('https://api.example.com/data', {
132
headers: {
133
'Authorization': 'Bearer token', // Added to defaults
134
'Accept': 'application/xml' // Overrides default
135
},
136
timeout: 60000 // Overrides default
137
// retry still uses default { retries: 2 }
138
});
139
140
// Final request has:
141
// Headers: User-Agent: MyApp/1.0, Accept: application/xml, Authorization: Bearer token
142
// Timeout: 60000
143
// Retry: { retries: 2 }
144
```
145
146
### Configuration Patterns
147
148
Common patterns for organizing fetch configurations:
149
150
```javascript
151
// Environment-based configuration
152
const createFetch = (env) => {
153
const baseConfig = {
154
cachePath: `./cache-${env}`,
155
retry: env === 'production' ? { retries: 5 } : { retries: 1 }
156
};
157
158
if (env === 'development') {
159
baseConfig.proxy = 'http://localhost:8888';
160
}
161
162
return fetch.defaults(baseConfig);
163
};
164
165
// Service-specific configuration
166
const apiConfig = {
167
cachePath: './api-cache',
168
timeout: 30000,
169
retry: { retries: 3, factor: 2 }
170
};
171
172
const imageConfig = {
173
cachePath: './image-cache',
174
timeout: 120000,
175
size: 50 * 1024 * 1024, // 50MB max
176
integrity: true // Enable integrity checking
177
};
178
179
const apiFetch = fetch.defaults(apiConfig);
180
const imageFetch = fetch.defaults(imageConfig);
181
182
// Authentication middleware pattern
183
const createAuthenticatedFetch = (getToken) => {
184
const baseFetch = fetch.defaults({
185
cachePath: './auth-cache',
186
retry: { retries: 2 }
187
});
188
189
return async (url, options = {}) => {
190
const token = await getToken();
191
return baseFetch(url, {
192
...options,
193
headers: {
194
...options.headers,
195
'Authorization': `Bearer ${token}`
196
}
197
});
198
};
199
};
200
```
201
202
### TypeScript Support
203
204
When using TypeScript, default functions maintain proper type safety:
205
206
```typescript
207
import fetch, { FetchOptions, Response } from 'make-fetch-happen';
208
209
// Type-safe default configuration
210
const apiConfig: FetchOptions = {
211
cachePath: './cache',
212
timeout: 30000,
213
headers: { 'Content-Type': 'application/json' }
214
};
215
216
const apiFetch = fetch.defaults('https://api.example.com', apiConfig);
217
218
// Return type is still Promise<Response>
219
const response: Promise<Response> = apiFetch('/users');
220
```