Isomorphic WHATWG Fetch API polyfill for Node.js and browser environments
npx @tessl/cli install tessl/npm-isomorphic-fetch@3.0.0Isomorphic 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.
npm install isomorphic-fetchrequire('isomorphic-fetch');
// After import, fetch is available globallyES6 modules:
import 'isomorphic-fetch';
// After import, fetch is available globallyBower:
// Bower installs to bower_components/isomorphic-fetch/fetch-bower.js
// This simply re-exports the fetch polyfill
<script src="bower_components/isomorphic-fetch/fetch-bower.js"></script>require('isomorphic-fetch');
fetch('//offline-news-api.herokuapp.com/stories')
.then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then(function(stories) {
console.log(stories);
});Isomorphic Fetch works as a polyfill that provides environment-specific implementations:
node-fetch internally, adds global objects, and normalizes protocol-relative URLs (// → https://)whatwg-fetch polyfill which adds fetch to the global scopeThe package automatically detects the runtime environment and provides the appropriate implementation without requiring different import patterns.
The main fetch function for making HTTP requests. Automatically added to global scope when the package is imported.
/**
* Make an HTTP request using the Fetch API
* @param {string|Request} url - URL to fetch or Request object
* @param {RequestInit} [options] - Optional request configuration
* @returns {Promise<Response>} Promise that resolves to the Response object
*/
function fetch(url: string | Request, options?: RequestInit): Promise<Response>;Platform-specific behavior:
//example.com) are automatically converted to https://example.comUsage Examples:
// Basic GET request
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
// POST request with JSON data
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'John Doe',
email: 'john@example.com'
})
})
.then(response => response.json())
.then(result => console.log(result));
// Protocol-relative URL (Node.js automatically converts to https://)
fetch('//api.example.com/data')
.then(response => response.text())
.then(text => console.log(text));
// Request with AbortSignal for cancellation
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
fetch('https://api.example.com/slow-endpoint', {
signal: controller.signal
})
.then(response => response.json())
.then(data => {
clearTimeout(timeoutId);
console.log(data);
})
.catch(error => {
if (error.name === 'AbortError') {
console.log('Request was cancelled');
} else {
console.error('Fetch error:', error);
}
});Response object constructor provided by the underlying fetch implementation. Available globally after importing isomorphic-fetch.
/**
* Response object representing the response to a request
* Available globally after importing isomorphic-fetch
*/
class Response {
constructor(body, init);
// Properties
readonly status: number;
readonly statusText: string;
readonly ok: boolean;
readonly headers: Headers;
readonly url: string;
readonly bodyUsed: boolean;
// Methods
json(): Promise<any>;
text(): Promise<string>;
blob(): Promise<Blob>;
arrayBuffer(): Promise<ArrayBuffer>;
clone(): Response;
}Headers object constructor for managing HTTP headers. Available globally after importing isomorphic-fetch.
/**
* Headers object for managing HTTP headers
* Available globally after importing isomorphic-fetch
*/
class Headers {
constructor(init);
append(name: string, value: string): void;
delete(name: string): void;
get(name: string): string | null;
has(name: string): boolean;
set(name: string, value: string): void;
forEach(callback: (value: string, name: string, headers: Headers) => void): void;
}Request object constructor for representing HTTP requests. Available globally after importing isomorphic-fetch.
/**
* Request object representing an HTTP request
* Available globally after importing isomorphic-fetch
*/
class Request {
constructor(input: string | Request, init?: RequestInit);
// Properties
readonly method: string;
readonly url: string;
readonly headers: Headers;
readonly body: ReadableStream | null;
readonly bodyUsed: boolean;
readonly cache: RequestCache;
readonly credentials: RequestCredentials;
readonly destination: RequestDestination;
readonly integrity: string;
readonly keepalive: boolean;
readonly mode: RequestMode;
readonly redirect: RequestRedirect;
readonly referrer: string;
readonly referrerPolicy: ReferrerPolicy;
// Methods
clone(): Request;
json(): Promise<any>;
text(): Promise<string>;
blob(): Promise<Blob>;
arrayBuffer(): Promise<ArrayBuffer>;
}/**
* Request initialization options
*/
interface RequestInit {
method?: string;
headers?: HeadersInit;
body?: BodyInit | null;
mode?: RequestMode;
credentials?: RequestCredentials;
cache?: RequestCache;
redirect?: RequestRedirect;
referrer?: string;
referrerPolicy?: ReferrerPolicy;
integrity?: string;
keepalive?: boolean;
signal?: AbortSignal | null;
}
/**
* Headers initialization types
*/
type HeadersInit = Headers | Record<string, string> | string[][];
/**
* Body content types
*/
type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream<Uint8Array> | string;
/**
* Request modes
*/
type RequestMode = "cors" | "no-cors" | "same-origin";
/**
* Credential modes
*/
type RequestCredentials = "omit" | "same-origin" | "include";
/**
* Cache modes
*/
type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached";
/**
* Redirect modes
*/
type RequestRedirect = "follow" | "error" | "manual";
/**
* Referrer policy types
*/
type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "same-origin" | "strict-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
/**
* Request destination types
*/
type RequestDestination = "" | "audio" | "audioworklet" | "document" | "embed" | "font" | "frame" | "iframe" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt";
/**
* Buffer source types
*/
type BufferSource = ArrayBuffer | ArrayBufferView;Isomorphic Fetch follows standard Fetch API error handling patterns:
response.ok or response.status)// URLs to https://fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));node-fetch (^2.6.1) internally with protocol normalizationwhatwg-fetch (^3.4.1) polyfill for Fetch API supportfetch-bower.js)fetch-npm-browserify.js)Dependencies:
node-fetch@^2.6.1 - Node.js fetch implementationwhatwg-fetch@^3.4.1 - Browser fetch polyfill