Install and import ofetch
mainTo use ofetch in your project, install it via your preferred package manager and import the ofetch function.
npx nypm i ofetchimport { ofetch } from "ofetch";repository·main·Indexed 26 days ago
https://github.com/unjs/ofetchA feature-rich fetch wrapper that works across Node.js, browsers, and workers. ofetch provides smart JSON parsing, automatic retries, request interceptors, and type safety. It includes utilities for managing base URLs and query parameters, as well as the ability to create custom fetch instances via ofetch.create.
To use ofetch in your project, install it via your preferred package manager and import the ofetch function.
npx nypm i ofetchimport { ofetch } from "ofetch";Proxy configuration depends on your runtime:
dispatcher option with undici's ProxyAgent.proxy option with a string URL.undici via npm specifiers.Environment Variables: Bun and Deno respect HTTP_PROXY and HTTPS_PROXY. Node.js requires NODE_USE_ENV_PROXY=1 for built-in proxy support.
// Node.js example using undici
import { ProxyAgent } from "undici";
const proxyAgent = new ProxyAgent("http://localhost:3128");
await ofetch("https://icanhazip.com", { dispatcher: proxyAgent });Use the timeout option to specify the maximum time in milliseconds to wait for a request before it is automatically aborted.
await ofetch("http://google.com/404", {
timeout: 3000, // Timeout after 3 seconds
});By default, ofetch retries once if the response status is in the default retry list (e.g., 408, 429, 500, etc.). For POST, PUT, PATCH, and DELETE methods, retries are disabled by default to avoid side effects unless you explicitly set a retry value.
Options:
retry: Number of retries (default is 1 for GET, 0 for others).retryDelay: Delay between retries in milliseconds (default is 0).retryStatusCodes: Array of custom status codes to trigger a retry.await ofetch("http://google.com/404", {
retry: 3,
retryDelay: 500, // ms
retryStatusCodes: [404, 500],
});When using POST, PUT, or PATCH methods, passing an object to the body option will automatically stringify it using JSON.stringify() and set the content-type: application/json and accept: application/json headers.
const { users } = await ofetch("/api/users", {
method: "POST",
body: { some: "json" },
});ofetch provides helpers to manage base URLs and query strings efficiently.
baseURL: Prepends the base URL to the request path.query (or params): Adds an object of key-value pairs as query search parameters.If you need access to the underlying response object (e.g., to read headers), use ofetch.raw instead of the standard ofetch call.
const response = await ofetch.raw("/sushi");
// Access properties like:
// response._data
// response.headersBy default, ofetch automatically parses JSON responses. For other content types, you can specify a responseType or provide a custom parseResponse function.
Supported responseType values:
blobarrayBuffertextstream (automatically sets duplex: "half" for streaming support)// Return text as is
await ofetch("/movie?lang=en", { parseResponse: (txt) => txt });
// Get the blob version of the response
await ofetch("/api/generate-image", { responseType: "blob" });
// Get the stream version of the response
await ofetch("/api/generate-image", { responseType: "stream" });ofetch.create to instantiate a new fetcher with pre-configured default options. This is useful for setting a common baseURL or shared interceptors.Interceptors allow you to hook into the lifecycle of a request. You can provide a single function or an array of functions to be called sequentially.
Available lifecycle hooks:
onRequest({ request, options }): Called before the request is sent.onRequestError({ request, options, error }): Called when the request fails.onResponse({ request, response, options }): Called after the response is received and parsed.onResponseError({ request, response, options }): Called when the response is received but response.ok is false.await ofetch("/api", {
async onRequest({ request, options }) {
// Log request and modify options
console.log("[fetch request]", request, options);
options.query = options.query || {};
options.query.t = new Date();
},
});ofetch throws an error if response.ok is false. You can access the parsed error body via error.data. To prevent ofetch from throwing on status errors, set ignoreResponseError: true.The FetchOptions interface defines the configuration available for every request. It extends standard RequestInit (excluding body) and includes specialized ofetch features:
baseURL: A string to prefix all requests.body: The request payload (supports RequestInit['body'] or a plain Record<string, any>).query: A Record<string, any> to be appended as query search parameters.responseType: Determines how the response is parsed. Supported values are json, blob, text, arrayBuffer, and stream.timeout: Request timeout in milliseconds.retry: Number of retry attempts, or false to disable.retryDelay: Delay between retries in milliseconds, or a function (context: FetchContext) => number.retryStatusCodes: An array of HTTP status codes that trigger a retry. Default is [408, 409, 425, 429, 500, 502, 503, 504].ignoreResponseError: Boolean to prevent throwing errors on non-2xx responses.parseResponse: A function (responseText: string) => any to manually parse the response body.dispatcher: (Node.js >= 18) An undici Dispatcher for custom connection pooling.agent: (Older Node.js) A custom agent for polyfills.