Isomorphic WHATWG Fetch API polyfill for Node.js and browser environments
npx @tessl/cli install tessl/npm-isomorphic-fetch@3.0.00
# Isomorphic Fetch
1
2
Isomorphic Fetch provides a WHATWG Fetch API polyfill that works consistently across Node.js and browser environments. It adds the `fetch` function and related objects to the global scope, enabling cross-platform HTTP requests using the same API regardless of runtime environment.
3
4
## Package Information
5
6
- **Package Name**: isomorphic-fetch
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install isomorphic-fetch`
10
11
## Core Imports
12
13
```javascript
14
require('isomorphic-fetch');
15
// After import, fetch is available globally
16
```
17
18
ES6 modules:
19
20
```javascript
21
import 'isomorphic-fetch';
22
// After import, fetch is available globally
23
```
24
25
Bower:
26
27
```javascript
28
// Bower installs to bower_components/isomorphic-fetch/fetch-bower.js
29
// This simply re-exports the fetch polyfill
30
<script src="bower_components/isomorphic-fetch/fetch-bower.js"></script>
31
```
32
33
## Basic Usage
34
35
```javascript
36
require('isomorphic-fetch');
37
38
fetch('//offline-news-api.herokuapp.com/stories')
39
.then(function(response) {
40
if (response.status >= 400) {
41
throw new Error("Bad response from server");
42
}
43
return response.json();
44
})
45
.then(function(stories) {
46
console.log(stories);
47
});
48
```
49
50
## Architecture
51
52
Isomorphic Fetch works as a polyfill that provides environment-specific implementations:
53
54
- **Node.js Environment**: Uses `node-fetch` internally, adds global objects, and normalizes protocol-relative URLs (`//` → `https://`)
55
- **Browser Environment**: Uses `whatwg-fetch` polyfill which adds fetch to the global scope
56
- **Bower Environment**: Simple re-export mechanism
57
58
The package automatically detects the runtime environment and provides the appropriate implementation without requiring different import patterns.
59
60
## Capabilities
61
62
### Global Fetch Function
63
64
The main fetch function for making HTTP requests. Automatically added to global scope when the package is imported.
65
66
```javascript { .api }
67
/**
68
* Make an HTTP request using the Fetch API
69
* @param {string|Request} url - URL to fetch or Request object
70
* @param {RequestInit} [options] - Optional request configuration
71
* @returns {Promise<Response>} Promise that resolves to the Response object
72
*/
73
function fetch(url: string | Request, options?: RequestInit): Promise<Response>;
74
```
75
76
**Platform-specific behavior:**
77
- **Node.js**: Protocol-relative URLs (`//example.com`) are automatically converted to `https://example.com`
78
- **Browser**: Uses native fetch or whatwg-fetch polyfill behavior
79
80
**Usage Examples:**
81
82
```javascript
83
// Basic GET request
84
fetch('https://api.example.com/data')
85
.then(response => response.json())
86
.then(data => console.log(data));
87
88
// POST request with JSON data
89
fetch('https://api.example.com/users', {
90
method: 'POST',
91
headers: {
92
'Content-Type': 'application/json',
93
},
94
body: JSON.stringify({
95
name: 'John Doe',
96
email: 'john@example.com'
97
})
98
})
99
.then(response => response.json())
100
.then(result => console.log(result));
101
102
// Protocol-relative URL (Node.js automatically converts to https://)
103
fetch('//api.example.com/data')
104
.then(response => response.text())
105
.then(text => console.log(text));
106
107
// Request with AbortSignal for cancellation
108
const controller = new AbortController();
109
const timeoutId = setTimeout(() => controller.abort(), 5000);
110
111
fetch('https://api.example.com/slow-endpoint', {
112
signal: controller.signal
113
})
114
.then(response => response.json())
115
.then(data => {
116
clearTimeout(timeoutId);
117
console.log(data);
118
})
119
.catch(error => {
120
if (error.name === 'AbortError') {
121
console.log('Request was cancelled');
122
} else {
123
console.error('Fetch error:', error);
124
}
125
});
126
```
127
128
### Global Response Object
129
130
Response object constructor provided by the underlying fetch implementation. Available globally after importing isomorphic-fetch.
131
132
```javascript { .api }
133
/**
134
* Response object representing the response to a request
135
* Available globally after importing isomorphic-fetch
136
*/
137
class Response {
138
constructor(body, init);
139
140
// Properties
141
readonly status: number;
142
readonly statusText: string;
143
readonly ok: boolean;
144
readonly headers: Headers;
145
readonly url: string;
146
readonly bodyUsed: boolean;
147
148
// Methods
149
json(): Promise<any>;
150
text(): Promise<string>;
151
blob(): Promise<Blob>;
152
arrayBuffer(): Promise<ArrayBuffer>;
153
clone(): Response;
154
}
155
```
156
157
### Global Headers Object
158
159
Headers object constructor for managing HTTP headers. Available globally after importing isomorphic-fetch.
160
161
```javascript { .api }
162
/**
163
* Headers object for managing HTTP headers
164
* Available globally after importing isomorphic-fetch
165
*/
166
class Headers {
167
constructor(init);
168
169
append(name: string, value: string): void;
170
delete(name: string): void;
171
get(name: string): string | null;
172
has(name: string): boolean;
173
set(name: string, value: string): void;
174
forEach(callback: (value: string, name: string, headers: Headers) => void): void;
175
}
176
```
177
178
### Global Request Object
179
180
Request object constructor for representing HTTP requests. Available globally after importing isomorphic-fetch.
181
182
```javascript { .api }
183
/**
184
* Request object representing an HTTP request
185
* Available globally after importing isomorphic-fetch
186
*/
187
class Request {
188
constructor(input: string | Request, init?: RequestInit);
189
190
// Properties
191
readonly method: string;
192
readonly url: string;
193
readonly headers: Headers;
194
readonly body: ReadableStream | null;
195
readonly bodyUsed: boolean;
196
readonly cache: RequestCache;
197
readonly credentials: RequestCredentials;
198
readonly destination: RequestDestination;
199
readonly integrity: string;
200
readonly keepalive: boolean;
201
readonly mode: RequestMode;
202
readonly redirect: RequestRedirect;
203
readonly referrer: string;
204
readonly referrerPolicy: ReferrerPolicy;
205
206
// Methods
207
clone(): Request;
208
json(): Promise<any>;
209
text(): Promise<string>;
210
blob(): Promise<Blob>;
211
arrayBuffer(): Promise<ArrayBuffer>;
212
}
213
```
214
215
## Types
216
217
```javascript { .api }
218
/**
219
* Request initialization options
220
*/
221
interface RequestInit {
222
method?: string;
223
headers?: HeadersInit;
224
body?: BodyInit | null;
225
mode?: RequestMode;
226
credentials?: RequestCredentials;
227
cache?: RequestCache;
228
redirect?: RequestRedirect;
229
referrer?: string;
230
referrerPolicy?: ReferrerPolicy;
231
integrity?: string;
232
keepalive?: boolean;
233
signal?: AbortSignal | null;
234
}
235
236
/**
237
* Headers initialization types
238
*/
239
type HeadersInit = Headers | Record<string, string> | string[][];
240
241
/**
242
* Body content types
243
*/
244
type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream<Uint8Array> | string;
245
246
/**
247
* Request modes
248
*/
249
type RequestMode = "cors" | "no-cors" | "same-origin";
250
251
/**
252
* Credential modes
253
*/
254
type RequestCredentials = "omit" | "same-origin" | "include";
255
256
/**
257
* Cache modes
258
*/
259
type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached";
260
261
/**
262
* Redirect modes
263
*/
264
type RequestRedirect = "follow" | "error" | "manual";
265
266
/**
267
* Referrer policy types
268
*/
269
type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "same-origin" | "strict-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
270
271
/**
272
* Request destination types
273
*/
274
type RequestDestination = "" | "audio" | "audioworklet" | "document" | "embed" | "font" | "frame" | "iframe" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt";
275
276
/**
277
* Buffer source types
278
*/
279
type BufferSource = ArrayBuffer | ArrayBufferView;
280
```
281
282
## Error Handling
283
284
Isomorphic Fetch follows standard Fetch API error handling patterns:
285
286
- **Network errors**: Promise rejects for network failures
287
- **HTTP error status codes**: Promise resolves normally (check `response.ok` or `response.status`)
288
- **Protocol normalization**: Node.js environment automatically converts `//` URLs to `https://`
289
290
```javascript
291
fetch('https://api.example.com/data')
292
.then(response => {
293
if (!response.ok) {
294
throw new Error(`HTTP error! status: ${response.status}`);
295
}
296
return response.json();
297
})
298
.then(data => console.log(data))
299
.catch(error => console.error('Fetch error:', error));
300
```
301
302
## Platform Compatibility
303
304
- **Node.js**: Uses `node-fetch` (^2.6.1) internally with protocol normalization
305
- **Browser**: Uses `whatwg-fetch` (^3.4.1) polyfill for Fetch API support
306
- **Bower**: Supported via separate entry point (`fetch-bower.js`)
307
- **Browserify**: Supported via browser field in package.json (`fetch-npm-browserify.js`)
308
309
**Dependencies:**
310
- `node-fetch@^2.6.1` - Node.js fetch implementation
311
- `whatwg-fetch@^3.4.1` - Browser fetch polyfill