or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-isomorphic-fetch

Isomorphic WHATWG Fetch API polyfill for Node.js and browser environments

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/isomorphic-fetch@3.0.x

To install, run

npx @tessl/cli install tessl/npm-isomorphic-fetch@3.0.0

index.mddocs/

Isomorphic Fetch

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.

Package Information

  • Package Name: isomorphic-fetch
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install isomorphic-fetch

Core Imports

require('isomorphic-fetch');
// After import, fetch is available globally

ES6 modules:

import 'isomorphic-fetch';
// After import, fetch is available globally

Bower:

// 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>

Basic Usage

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);
  });

Architecture

Isomorphic Fetch works as a polyfill that provides environment-specific implementations:

  • Node.js Environment: Uses node-fetch internally, adds global objects, and normalizes protocol-relative URLs (//https://)
  • Browser Environment: Uses whatwg-fetch polyfill which adds fetch to the global scope
  • Bower Environment: Simple re-export mechanism

The package automatically detects the runtime environment and provides the appropriate implementation without requiring different import patterns.

Capabilities

Global Fetch Function

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:

  • Node.js: Protocol-relative URLs (//example.com) are automatically converted to https://example.com
  • Browser: Uses native fetch or whatwg-fetch polyfill behavior

Usage 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);
    }
  });

Global Response Object

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;
}

Global Headers Object

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;
}

Global Request Object

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>;
}

Types

/**
 * 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;

Error Handling

Isomorphic Fetch follows standard Fetch API error handling patterns:

  • Network errors: Promise rejects for network failures
  • HTTP error status codes: Promise resolves normally (check response.ok or response.status)
  • Protocol normalization: Node.js environment automatically converts // 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));

Platform Compatibility

  • Node.js: Uses node-fetch (^2.6.1) internally with protocol normalization
  • Browser: Uses whatwg-fetch (^3.4.1) polyfill for Fetch API support
  • Bower: Supported via separate entry point (fetch-bower.js)
  • Browserify: Supported via browser field in package.json (fetch-npm-browserify.js)

Dependencies:

  • node-fetch@^2.6.1 - Node.js fetch implementation
  • whatwg-fetch@^3.4.1 - Browser fetch polyfill