unfetch

repository·main·Indexed 26 days ago

https://github.com/developit/unfetch

A bare minimum Fetch API polyfill (~500b gzipped) designed for modern and legacy browsers (IE8+). It provides a familiar subset of the Fetch API using XMLHttpRequest. The repository also includes isomorphic-unfetch, which provides a universal fetch implementation by automatically switching between unfetch for the client and node-fetch 3.x for Node.js (version 12.20.0 or higher).

Tokens
2K
Snippets
7
Records
13
Agent score
90%

What's inside unfetch

  1. Use isomorphic-unfetch to polyfill global fetch

    main

    Importing isomorphic-unfetch automatically polyfills the global fetch object. It detects the environment and applies the appropriate implementation:

    • In Browser environments: It uses the existing global.fetch if available, otherwise it uses unfetch.
    • In Node.js environments: It dynamically imports node-fetch to provide a fetch implementation.

    When using the Node.js implementation, if the url provided is a string or URL instance starting with // (protocol-relative), it is automatically converted to use https://.

  2. Use isomorphic-unfetch in the browser to polyfill global fetch

    main
    The isomorphic-unfetch/browser.js entrypoint is designed for browser environments. It checks if self.fetch is already defined; if not, it polyfills the global self.fetch object using the unfetch package. This allows you to use standard fetch syntax in environments where it is missing.
  3. Use isomorphic-unfetch as a polyfill

    main

    To use isomorphic-unfetch as a polyfill, simply import the module. This will install fetch globally if it is not already available in the environment.

    import "isomorphic-unfetch";
    
    // "fetch" is now installed globally if it wasn't already available
    
    fetch("/foo.json")
      .then((r) => r.json())
      .then((data) => {
        console.log(data);
      });
  4. Use isomorphic-unfetch as a ponyfill

    main

    To use isomorphic-unfetch as a ponyfill, import the default export and use it as your fetch function. This allows you to switch between unfetch (for the client) and node-fetch (for the server) automatically.

    import fetch from "isomorphic-unfetch";
    
    fetch("/foo.json")
      .then((r) => r.json())
      .then((data) => {
        console.log(data);
      });
  5. Use unfetch for making HTTP requests

    main

    The default export of unfetch is a function that mimics the fetch API using XMLHttpRequest. It returns a Promise that resolves to a Response-like object.

    Function Signature

    unfetch(url, options)

    Parameters

    • url (string): The URL for the request.
    • options (Object): Configuration for the request.
      • method (string): The HTTP method (e.g., 'get', 'post'). Defaults to 'get'.
      • headers (Object): An object containing header keys and values to be sent with the request.
      • body (any): The request body to send.
      • credentials (string): Controls whether cookies are sent. Set to 'include' to enable credentials.

    Response Object

    The resolved promise provides an object with the following properties and methods:

    • ok (boolean): true if the status code is in the 200-299 range.
    • status (number): The HTTP status code.
    • statusText (string): The HTTP status text.
    • url (string): The URL of the response.
    • text() (function): Returns a Promise resolving to the response body as a string.
    • json() (function): Returns a Promise resolving to the parsed JSON body.
    • blob() (function): Returns a Promise resolving to a Blob of the response.
    • clone() (function): Returns a clone of the response object.
    • headers (object): An object providing access to response headers via:
      • keys(): Returns an array of header names.
      • entries(): Returns an array of [key, value] pairs.
      • get(name): Returns the value of the specified header.
      • has(name): Returns true if the header exists.
  6. Use isomorphic-unfetch to provide a universal fetch implementation

    main

    Importing isomorphic-unfetch attaches a fetch implementation to the global object. It automatically detects the environment and selects the appropriate implementation:

    • In Browser/Web Worker environments: It dynamically imports unfetch.
    • In Node.js environments: It dynamically imports node-fetch and automatically upgrades insecure // URLs to https://.

    This allows you to write code using the standard fetch API that works seamlessly across both client and server environments.

  7. Use isomorphic-unfetch in browser environments

    main
    The isomorphic-unfetch/browser entrypoint provides a way to ensure a fetch implementation is available on the global self object in browser environments. It imports fetch from unfetch and assigns it to self.fetch if it is not already defined. This is useful for ensuring consistent fetch behavior across different browser environments.
  8. Understand isomorphic-unfetch type compatibility

    main

    When using isomorphic-unfetch, the library provides types that are compatible with both the standard Web API fetch (used in browsers) and the node-fetch implementation (used in Node.js). This allows you to write code that works in both environments without type errors.

    The following types are unified under the unfetch namespace:

    • IsomorphicHeaders: Accepts Headers or NodeHeaders.
    • IsomorphicBody: Accepts Body or NodeBody.
    • IsomorphicResponse: Accepts Response or NodeResponse.
    • IsomorphicRequest: Accepts Request or NodeRequest.
    • IsomorphicRequestInit: Accepts RequestInit or NodeRequestInit.
    // The isomorphic types available in the unfetch namespace:
    type IsomorphicHeaders = Headers | NodeHeaders;
    type IsomorphicBody = Body | NodeBody;
    type IsomorphicResponse = Response | NodeResponse;
    type IsomorphicRequest = Request | NodeRequest;
    type IsomorphicRequestInit = RequestInit | NodeRequestInit;
  9. UnfetchHeaders interface

    main

    The UnfetchHeaders interface defines the available methods for interacting with response headers. Note that several standard Headers methods are explicitly not supported by unfetch and are marked as never to prevent usage.

    export interface UnfetchHeaders {
    	keys: () => string[];
    	entries: () => [string, string][];
    	get: (key: string) => string | null;
    	has: (key: string) => boolean;
    }
  10. UnfetchRequestInit interface

    main

    The UnfetchRequestInit interface defines the options used to initialize a request. Only a subset of the standard RequestInit is supported. Standard options like cache, integrity, keepalive, mode, redirect, referrer, referrerPolicy, and signal are not supported.

    export interface UnfetchRequestInit {
    	method?: string;
    	headers?: Record<string, string>;
    	credentials?: "include" | "omit";
    	body?: Parameters<XMLHttpRequest["send"]>[0];
    }