cross-fetch: Universal WHATWG Fetch

4.1.0 · active · verified Sun Apr 19

cross-fetch provides a universal implementation of the WHATWG Fetch API, making it available consistently across Node.js, modern web browsers, and React Native environments. It currently maintains version 4.1.0 and is actively developed, with frequent patch and minor releases, alongside major version updates to support new Node.js runtimes and integrate updates from its underlying `node-fetch` and `whatwg-fetch` dependencies. Its primary differentiator is simplifying HTTP requests by abstracting away environment-specific `fetch` implementations, allowing developers to write isomorphic code without conditional imports or manual polyfill management. This ensures that `fetch` behaves predictably whether executed server-side or client-side, addressing common challenges in full-stack JavaScript applications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to perform both GET and POST requests using `cross-fetch` in an asynchronous function, including basic error handling.

import { fetch } from 'cross-fetch';

async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log('Fetched data:', data);

    // Example with POST request
    const postResponse = await fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        title: 'foo',
        body: 'bar',
        userId: 1,
      }),
    });
    if (!postResponse.ok) {
      throw new Error(`HTTP error! status: ${postResponse.status}`);
    }
    const postData = await postResponse.json();
    console.log('Posted data:', postData);

  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

fetchData();

view raw JSON →