ofetch will smartly parse JSON and native values using destr, falling back to the text if it fails to parse.
const { users } = await ofetch("/api/users");
For binary content types, ofetch will instead return a Blob object.
You can optionally provide a different parser than destr, or specify blob, arrayBuffer, text or stream to force parsing the body with the respective FetchResponse method.
// Use JSON.parseawait ofetch("/movie?lang=en", { parseResponse: JSON.parse });// Return text as isawait ofetch("/movie?lang=en", { parseResponse: (txt) => txt });// Get the blob version of the responseawait ofetch("/api/generate-image", { responseType: "blob" });// Get the stream version of the responseawait ofetch("/api/generate-image", { responseType: "stream" });
✔️ JSON Body
If an object or a class with a .toJSON() method is passed to the body option, ofetch automatically stringifies it.
ofetch utilizes JSON.stringify() to convert the passed object. Classes without a .toJSON() method have to be converted into a string value in advance before being passed to the body option.
For PUT, PATCH, and POST request methods, when a string or object body is set, ofetch adds the default "content-type": "application/json" and accept: "application/json" headers (which you can always override).
Additionally, ofetch supports binary responses with Buffer, ReadableStream, Stream, and compatible body types. ofetch will automatically set the duplex: "half" option for streaming support!
You can specify the amount of retry and delay between them using retry and retryDelay options and also pass a custom array of codes using retryStatusCodes option.
The default for retry is 1 retry, except for POST, PUT, PATCH, and DELETE methods where ofetch does not retry by default to avoid introducing side effects. If you set a custom value for retry it will always retry for all requests.
The default for retryDelay is 0 ms.
await ofetch("http://google.com/404", { retry: 3, retryDelay: 500, // ms retryStatusCodes: [ 404, 500 ], // response status codes to retry});
✔️ Timeout
You can specify timeout in milliseconds to automatically abort a request after a timeout (default is disabled).
await ofetch("http://google.com/404", { timeout: 3000, // Timeout after 3 seconds});
✔️ Type Friendly
The response can be type assisted:
const article = await ofetch<Article>(`/api/article/${id}`);// Auto complete working with article.id
✔️ Adding baseURL
By using baseURL option, ofetch prepends it for trailing/leading slashes and query search params for baseURL using ufo:
await ofetch("/config", { baseURL });
✔️ Adding Query Search Params
By using query option (or params as alias), ofetch adds query search params to the URL by preserving the query in the request itself using ufo:
const stream = await ofetch("/sse")const reader = stream.getReader();const decoder = new TextDecoder()while (true) { const { done, value } = await reader.read(); if (done) break; // Here is the chunked text of the SSE response. const text = decoder.decode(value)}
🕵️ Adding HTTP(S) Agent
In Node.js (>= 18) environments, you can provide a custom dispatcher to intercept requests and support features such as Proxy and self-signed certificates. This feature is enabled by undici built-in Node.js. read more about the Dispatcher API.
Some available agents:
ProxyAgent: A Proxy Agent class that implements the Agent API. It allows the connection through a proxy in a simple way. (docs)
MockAgent: A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. (docs)
Agent: Agent allows dispatching requests against multiple different origins. (docs)
Example: Set a proxy agent for one request:
import { ProxyAgent } from "undici";import { ofetch } from "ofetch";const proxyAgent = new ProxyAgent("http://localhost:3128");const data = await ofetch("https://icanhazip.com", { dispatcher: proxyAgent });
Example: Create a custom fetch instance that has proxy enabled:
import { ProxyAgent, setGlobalDispatcher } from "undici";import { ofetch } from "ofetch";const proxyAgent = new ProxyAgent("http://localhost:3128");const fetchWithProxy = ofetch.create({ dispatcher: proxyAgent });const data = await fetchWithProxy("https://icanhazip.com");
Example: Set a proxy agent for all requests:
import { ProxyAgent, setGlobalDispatcher } from "undici";import { ofetch } from "ofetch";const proxyAgent = new ProxyAgent("http://localhost:3128");setGlobalDispatcher(proxyAgent);const data = await ofetch("https://icanhazip.com");
Example: Allow self-signed certificates (USE AT YOUR OWN RISK!)
import { Agent } from "undici";import { ofetch } from "ofetch";// Note: This makes fetch unsecure against MITM attacks. USE AT YOUR OWN RISK!const unsecureAgent = new Agent({ connect: { rejectUnauthorized: false } });const unsecureFetch = ofetch.create({ dispatcher: unsecureAgent });const data = await unsecureFetch("https://www.squid-cache.org/");
On older Node.js version (<18), you might also use use agent:
import { HttpsProxyAgent } from "https-proxy-agent";await ofetch("/api", { agent: new HttpsProxyAgent("http://example.com"),});
keepAlive support (only works for Node < 18)
By setting the FETCH_KEEP_ALIVE environment variable to true, an HTTP/HTTPS agent will be registered that keeps sockets around even when there are no outstanding requests, so they can be used for future requests without having to re-establish a TCP connection.
You can augment the FetchOptions interface to add custom properties.
// Place this in any `.ts` or `.d.ts` file.// Ensure it's included in the project's tsconfig.json "files".declare module "ofetch" { interface FetchOptions { // Custom properties requiresAuth?: boolean; }}export {}
This lets you pass and use those properties with full type safety throughout ofetch calls.
All targets are exported with Module and CommonJS format and named exports
No export is transpiled for the sake of modern syntax
You probably need to transpile ofetch, destr, and ufo packages with Babel for ES5 support
You need to polyfill fetch global for supporting legacy browsers like using unfetch
❓ FAQ
Why export is called ofetch instead of fetch?
Using the same name of fetch can be confusing since API is different but still, it is a fetch so using the closest possible alternative. You can, however, import { fetch } from ofetch which is auto-polyfill for Node.js and using native otherwise.
Why not have default export?
Default exports are always risky to be mixed with CommonJS exports.
This also guarantees we can introduce more utils without breaking the package and also encourage using ofetch name.
Why not transpiled?
By transpiling libraries, we push the web backward with legacy code which is unneeded for most of the users.
If you need to support legacy users, you can optionally transpile the library in your build pipeline.