Node.js `fetch` Compatibility Layer

1.6.7 · active · verified Sun Apr 19

node-fetch-native is a lightweight package designed to provide a consistent `fetch` API across various JavaScript runtimes, primarily targeting Node.js. It intelligently prefers Node.js's experimental native `fetch` (backed by `undici`) when available, falls back to an internal `node-fetch v3` implementation for older Node.js versions, and offers comprehensive HTTP/HTTPS proxy support, which is not natively available in Node.js's built-in `fetch` implementation. Currently stable at version `1.6.7`, the package maintains a steady release cadence, often addressing dependency updates and minor bug fixes. A key differentiator is its ability to bridge the `CommonJS` (`require`) and `ESM` (`import`) divide for `fetch`, resolving common migration issues encountered with `node-fetch` v3. It also provides a polyfill mechanism to ensure global `fetch` availability.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic `fetch` usage, fetching with named `Headers` and `Request` objects, and shows how `node-fetch-native` inherently supports HTTP/HTTPS proxies when `HTTP_PROXY` or `HTTPS_PROXY` environment variables are configured. It highlights both default and named imports.

import fetch, { Headers, Request } from 'node-fetch-native';
import 'node-fetch-native/polyfill'; // Optional: ensures global fetch is available

async function runExample() {
  console.log("--- Basic Fetch Example ---");
  try {
    const response = await fetch("https://api.github.com/zen");
    const text = await response.text();
    console.log(`GitHub Zen says: "${text}"`);
  } catch (error) {
    console.error("Basic fetch failed:", error);
  }

  console.log("\n--- Fetch with Named Exports Example ---");
  try {
    const headers = new Headers({ "Content-Type": "application/json" });
    const request = new Request("https://jsonplaceholder.typicode.com/posts", {
      method: "POST",
      headers: headers,
      body: JSON.stringify({ title: "foo", body: "bar", userId: 1 }),
    });
    const response = await fetch(request);
    const data = await response.json();
    console.log("POST request response:", data);
  } catch (error) {
    console.error("Named exports fetch failed:", error);
  n}

  // Example of using a proxy (requires setting environment variables like HTTP_PROXY)
  if (process.env.HTTP_PROXY || process.env.HTTPS_PROXY) {
    console.log("\n--- Proxy-aware Fetch (if env vars are set) ---");
    try {
      const response = await fetch("http://example.com");
      console.log(`Fetched http://example.com via proxy (status: ${response.status})`);
    } catch (error) {
      console.error("Proxy fetch failed:", error);
    }
  } else {
    console.log("\n--- Proxy-aware Fetch: Set HTTP_PROXY or HTTPS_PROXY environment variable to test. ---");
    console.log("Example: export HTTP_PROXY=http://localhost:8080");
  }
}

runExample();

view raw JSON →