Isomorphic Fetch API

4.0.2 · active · verified Sun Apr 19

Isomorphic Unfetch is a lightweight JavaScript library that provides a universal `fetch` API implementation, automatically switching between `unfetch` (a minimal `fetch` ponyfill for browsers) and `node-fetch` (a `fetch` implementation for Node.js) based on the execution environment. The current stable version is 5.0.0. This package aims for a small footprint and consistent behavior across client-side and server-side JavaScript, abstracting away environment-specific `fetch` implementations. It provides both a ponyfill (default named import) and a global polyfill (side-effect import). Recent major updates include the adoption of `node-fetch` v3.x, which mandates Node.js >= 12.20.0, and the addition of first-class TypeScript definitions and Package Exports for improved module resolution. It focuses on simplicity and compatibility with standard `fetch` API usage.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `isomorphic-unfetch` as a ponyfill to make `GET` requests, handle responses, and includes basic TypeScript typing for typical `fetch` API usage.

import fetch from "isomorphic-unfetch";
import type { RequestInit, Response } from 'isomorphic-unfetch';

interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}

async function getExamplePosts(postId: number = 1): Promise<Post | Post[]> {
  // Use a public API for demonstration
  const url = `https://jsonplaceholder.typicode.com/posts/${postId}`;
  const options: RequestInit = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    // body: JSON.stringify({ key: 'value' }) // Example for POST/PUT
  };

  try {
    const response: Response = await fetch(url, options);

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const data = await response.json();
    console.log(`Fetched post(s) from ${url}:`, data);
    return data;
  } catch (error) {
    console.error("Error fetching data:", error);
    throw error;
  }
}

// Example usage
getExamplePosts(1)
  .then(() => getExamplePosts(2))
  .then(() => getExamplePosts()) // Fetch all posts example, though API usually limits
  .catch(err => console.error("An error occurred during quickstart execution:", err));

// Optional: Global polyfill usage example if you need `fetch` on global scope:
// import 'isomorphic-unfetch/polyfill';
// // Now `fetch` is globally available for other parts of your app
// // For example, `globalThis.fetch` or `window.fetch`

view raw JSON →