Node & Browser Support
Node.js 22 and modern browsers provide fetch by default. api-def uses FetchRequestBackend automatically when the runtime supports fetch, Request, Response, and Headers. In browser environments without supported fetch, it falls back to XHRRequestBackend when XMLHttpRequest is available. In other environments, provide a compatible request backend:
Fetch Backend
In older versions of Node.JS you may need to provide your own fetch implementation.
You can provide a fetch implementation to api-def by setting the request backend:
import { Api, FetchRequestBackend, setRequestBackend } from "api-def";
setRequestBackend(new FetchRequestBackend(fetch));
const API = new Api({
name: "My Backend",
baseUrl: "https://api.example.com",
});
export default API;
Install and provide a fetch-compatible implementation when targeting an older runtime:
npm install cross-fetch
You can check native support before choosing a backend:
FetchRequestBackend.isSupported();
XHRRequestBackend.isSupported();
AxiosRequestBackend.isSupported(axios);
Axios Backend
import axios from "axios";
import { setRequestBackend, AxiosRequestBackend, Api } from "api-def";
// set the request backend and pass in your version of axios
setRequestBackend(new AxiosRequestBackend(axios));
const API = new Api({
/* ... */
});
export default API;
Install Axios separately when using AxiosRequestBackend:
npm install axios
XHR Backend
Use XHRRequestBackend directly in browsers that need XMLHttpRequest support instead of fetch:
import { Api, setRequestBackend, XHRRequestBackend } from "api-def";
setRequestBackend(new XHRRequestBackend());
const API = new Api({
name: "My Backend",
baseUrl: "https://api.example.com",
});
The XHR backend supports text, JSON, and ArrayBuffer responses. Set responseType: "arraybuffer" for binary endpoints so XHR can preserve the response bytes. It does not support streaming responses; use FetchRequestBackend for streams. credentials: "include" maps to XMLHttpRequest.withCredentials; browsers do not let XHR omit same-origin cookies.