User Configurable Fetch Implementation
Can be used as a global fetch implementation or as a local fetch implementation specific to a package.
Adapters
Usage
The default fetch implementation is globalThis.fetch
. Which works in almost all modern environments (browsers, Node.js, Deno, Cloudflare Workers, etc).
import fetch from "@fetch-impl/fetcher";
fetch("https://example.com").then(async (res) => {
console.log(res.status, await res.text());
});
You can replace the default fetch implementation with a custom one using fetcher.set
:
import fetch, { fetcher } from "@fetch-impl/fetcher";
fetcher.set(async (...args) => {
return new Response("Hello, World!", { status: 200 });
});
fetch("https://example.com").then(async (res) => {
console.log(res.status, await res.text());
});
If you are a package author and want to let your users configure the fetch implementation, you can use Fetcher
to create a configurable local fetch implementation:
import { Fetcher } from "@fetch-impl/fetcher";
export const fetcher = new Fetcher();
export const fetch = (...args) => fetcher.fetch(...args);
export default fetch;
import fetch from "./fetch";
export async function makeRequest(url: string): Promise<string> {
const res = await fetch(url);
return res.text();
}
export * from "./fetch";
Your users can then configure the fetch implementation like this:
import { makeRequest, fetcher } from "your-package";
import { useCrossFetch } from "@fetch-impl/cross-fetch";
useCrossFetch(fetcher);
makeRequest("https://example.com").then((text) => {
console.log(text);
});