Skip to content

OFetch - A Better Fetch API

NPM Last Update NPM Downloads NPM Version

OFetch is a lightweight and modern library for making HTTP requests, designed as an improved alternative to the native fetch API. It offers a simpler syntax, better error handling, and advanced features like request cancellation, interceptors, and automatic JSON data handling.


Install ofetch via npm or yarn:

Terminal window
npm install ofetch
# or
yarn add ofetch

import { ofetch } from "ofetch";
const data = await ofetch("https://api.example.com/users");
console.log(data);
const newUser = await ofetch("https://api.example.com/users", {
method: "POST",
body: { name: "Alice", age: 30 },
});
console.log(newUser);

try {
const data = await ofetch("https://api.example.com/unknown");
} catch (error) {
console.error("Error:", error);
}
const client = ofetch.create({
onRequest({ options }) {
options.headers = { ...options.headers, Authorization: "Bearer token" };
},
});
const data = await client("https://api.example.com/protected");
const controller = new AbortController();
const promise = ofetch("https://api.example.com/long-request", {
signal: controller.signal,
});
// Cancel the request after 1 second
setTimeout(() => controller.abort(), 1000);

  • Reuse Instances: Create configured instances to avoid repeating options.
  • Handle Errors: Use try/catch to capture HTTP errors.
  • Optimize Requests: Use interceptors to add headers or logs.

For more details, check out the OFetch official documentation.