node-fetch-native

repository·main·Indexed 41 days ago

https://github.com/unjs/node-fetch-native

A redistribution of node-fetch v3 designed for improved backward and forward compatibility across JavaScript runtimes. It supports both ESM and CommonJS, prefers native globals when available, and provides built-in proxy support for Node.js environments via utilities like createFetch and createProxy. Version 1.6.7.

Tokens
4.4K
Snippets
21
Records
25
Agent score
50%

What's inside node-fetch-native

  1. Use fetch with proxy support

    main

    This package provides proxy support for both Node.js versions with and without native fetch.

    By default, it checks the following environment variables for proxy configuration (in order):

    • https_proxy
    • http_proxy
    • HTTPS_PROXY
    • HTTP_PROXY

    It also respects no_proxy and NO_PROXY for host exclusion. You can override these using the url and noProxy options in the utility functions.

  2. Alias node-fetch to node-fetch-native in package managers

    main

    To ensure all project dependencies benefit from node-fetch-native and to prevent conflicts between node-fetch@2 and node-fetch@3, you can alias node-fetch in your package.json using your package manager's override feature.

    // npm (overrides)
    {
      "overrides": {
        "node-fetch": "npm:node-fetch-native@latest"
      }
    }
    
    // yarn (resolutions)
    {
      "resolutions": {
        "node-fetch": "npm:node-fetch-native@latest"
      }
    }
    
    // pnpm (pnpm.overrides)
    {
      "pnpm": {
        "overrides": {
          "node-fetch": "npm:node-fetch-native@latest"
        }
      }
    }
  3. Use the polyfill to enable global fetch

    main

    You can ensure fetch is available globally across your entire environment by importing the polyfill. Note: This is not recommended for library authors; prefer explicit imports instead.

    // ESM
    import "node-fetch-native/polyfill";
    
    // CJS
    require("node-fetch-native/polyfill");
    
    // You can now use fetch() without any import!
  4. Install node-fetch-native

    main

    Install node-fetch-native using your preferred package manager to gain improved compatibility for node-fetch in both ESM and CommonJS environments.

    # npm
    npm i node-fetch-native
    
    # yarn
    yarn add node-fetch-native
    
    # pnpm
    pnpm i node-fetch-native
  5. Force using the non-native node-fetch implementation

    main

    If you encounter issues with the native/polyfill globalThis.fetch in your runtime, you can explicitly use the node-fetch implementation via one of two methods:

    1. Set the FORCE_NODE_FETCH environment variable before starting your application.
    2. Import directly from node-fetch-native/node.
  6. Implement proxy support with fetch utilities

    main

    There are three ways to implement proxy support:

    1. Preconfigured fetch: Import { fetch } from node-fetch-native/proxy for a version of fetch that automatically uses environment-based proxy settings.
    2. createFetch: Use this utility to create a custom fetch instance with a specific proxy url.
    3. createProxy: Use this to generate an object containing agent and dispatcher keys, which can be passed directly into the standard fetch options.
    // 1. Preconfigured fetch
    import { fetch } from "node-fetch-native/proxy";
    await fetch("https://icanhazip.com");
    
    // 2. createFetch utility
    import { createFetch } from "node-fetch-native/proxy";
    const fetch = createFetch({ url: "http://localhost:9080" });
    await fetch("https://icanhazip.com");
    
    // 3. createProxy utility
    import { fetch } from "node-fetch-native";
    import { createProxy } from "node-fetch-native/proxy";
    const proxy = createProxy({ url: "http://localhost:8080" });
    await fetch("https://icanhazip.com", { ...proxy });
  7. Import fetch and related web APIs

    main

    You can import the default fetch or specific web API globals like Blob, FormData, Headers, Request, Response, and AbortController using either ESM or CommonJS syntax.

    // ESM
    import fetch from "node-fetch-native";
    // or
    import {
      fetch,
      Blob,
      FormData,
      Headers,
      Request,
      Response,
      AbortController,
    } from "node-fetch-native";
    
    // CommonJS
    const fetch = require("node-fetch-native");
    // or
    const {
      fetch,
      Blob,
      FormData,
      Headers,
      Request,
      Response,
      AbortController,
    } = require("node-fetch-native");
  8. Force using the non-native fetch implementation

    main

    If you want to bypass the native globalThis.fetch and ensure the node-fetch-native implementation is used (for example, to ensure consistent behavior across different Node.js versions or environments), set the FORCE_NODE_FETCH environment variable to true in your process environment.

    # Example for running a script with the forced implementation
    FORCE_NODE_FETCH=true node your-script.js
  9. Configure ESLint with eslint-config-unjs

    main

    This project uses eslint-config-unjs for its linting configuration. You can extend this configuration in your own eslint.config.mjs by importing the unjs config function and passing an options object to customize ignores and rules.

    import unjs from "eslint-config-unjs";
    
    export default unjs({
      ignores: [
        "path/to/file.mjs"
      ],
      rules: {
        "rule-name": 0,
      },
    });
  10. Use createFetch to create a proxy-aware fetch function

    main

    The createFetch utility allows you to create a pre-configured fetch function that automatically applies proxy settings to every request. This is the easiest way to use node-fetch-native with a proxy.

    Pass a ProxyOptions object to createFetch to specify the proxy URL and bypass list.

    import { createFetch } from 'node-fetch-native';
    
    const fetchWithProxy = createFetch({
      url: 'http://my-proxy.com:8080',
      noProxy: ['localhost']
    });
    
    // Use it just like the standard fetch API
    const response = await fetchWithProxy('https://api.example.com/data');
    const data = await response.json();
  11. Configure proxy support with createProxy

    main

    Use createProxy to generate the necessary agents for proxying HTTP requests. It returns an object containing both an agent (for standard Node.js http/https usage) and a dispatcher (for undici-based usage).

    It automatically resolves the proxy URL from the following order of precedence:

    1. opts.url
    2. process.env.https_proxy / process.env.http_proxy / process.env.HTTPS_PROXY / process.env.HTTP_PROXY

    It also handles proxy bypasses via noProxy (from opts.noProxy or environment variables no_proxy/NO_PROXY), which accepts a string of comma-separated hosts or an array of strings.

    import { createProxy } from 'node-fetch-native';
    
    const proxy = createProxy({
      url: 'http://my-proxy.com:8080',
      noProxy: ['localhost', '127.0.0.1', '.internal.corp']
    });
    
    // proxy.agent can be used with standard Node.js http/https
    // proxy.dispatcher can be used with undici