Registry / http-networking / ofetch

ofetch

JSON →
library1.5.1jsnpmunverified

ofetch is a modern, cross-platform HTTP client that provides a simplified, "better fetch API" for Node.js, browsers, and web workers. It intelligently handles request and response parsing, automatically stringifying JSON bodies and parsing responses using `destr` for robustness. Key features include automatic error throwing with detailed `FetchError` objects, built-in retry mechanisms for transient network issues and specific status codes, and seamless handling of binary and stream responses. The current stable version is 1.5.1, with a major v2.0.0 release in alpha that will transition to an ESM-only architecture, remove external dependencies, and further reduce bundle size. ofetch differentiates itself by offering a consistent, feature-rich `fetch` experience across diverse JavaScript environments, abstracting away common boilerplate and error handling patterns.

npm install ofetch
INSTALL
IMPORT
SIG · OFETCH
O
ofetch
http-networkingjavascriptv1.5.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ofetch
import { ofetch } from 'ofetch'
const { ofetch } = require('ofetch')
CommonJS `require` will no longer be supported in `ofetch` v2.0.0, which is currently in alpha and will be ESM-only.
FetchError
import type { FetchError } from 'ofetch'
import { FetchError } from 'ofetch'
Import `FetchError` as a type for robust TypeScript error handling. It's a type, not a runtime class that needs to be imported directly for instantiation.
createFetch
import { createFetch } from 'ofetch'
Use `createFetch` to create a new `ofetch` instance with custom default options, useful for API wrappers.

Demonstrates basic GET and POST requests, handling JSON bodies, custom headers, error catching with `FetchError`, and fetching binary data as a Blob, highlighting `ofetch`'s versatility.

import { ofetch, type FetchError } from "ofetch"; // Example of a GET request async function getUserData() { try { const users = await ofetch("https://jsonplaceholder.typicode.com/users"); console.log("Fetched users:", users.map(u => u.name)); } catch (error) { if (error instanceof FetchError) { console.error("GET Error data:", error.data); } else { console.error("GET Unknown error:", error); } } } // Example of a POST request with JSON body and custom headers async function createUser() { const newUser = { name: "John Doe", username: "johndoe", email: "john.doe@example.com", }; try { const response = await ofetch("https://jsonplaceholder.typicode.com/users", { method: "POST", body: newUser, headers: { "X-Client-ID": process.env.CLIENT_ID ?? 'default-client' }, }); console.log("Created user with ID:", response.id); } catch (error) { if (error instanceof FetchError) { console.error("POST Error data:", error.data); } else { console.error("POST Unknown error:", error); } } } // Example of fetching a binary response (e.g., an image blob) async function fetchImageBlob() { try { const imageBlob = await ofetch("https://via.placeholder.com/150", { responseType: "blob", baseURL: "https://example.com" }); console.log(`Fetched image blob of type: ${imageBlob.type} and size: ${imageBlob.size} bytes`); // In a browser, you could then use URL.createObjectURL(imageBlob) to display it. } catch (error) { console.error("Image fetch error:", error); } } async function runExamples() { await getUserData(); await createUser(); await fetchImageBlob(); } runExamples();
Debug
Known issues
breakingStarting with `ofetch` v2.0.0 (currently in alpha), the package will be ESM-only. This means CommonJS `require()` statements will no longer work, and projects must use ES module `import` syntax.
fix
Migrate your project to use ES module `import` syntax. For Node.js, ensure your `package.json` has `"type": "module"` or use `.mjs` file extensions.
affects: >=2.0.0-alpha.1
gotchaSince `ofetch` v1.4.0, `ctx.options.headers` within interceptors is always normalized to a standard `Headers` object. If your code previously depended on `HeadersInit` types (like plain objects or arrays) within interceptor logic, it might need adjustments.
fix
Ensure that any logic interacting with `ctx.options.headers` in `onRequest` or `onResponse` hooks explicitly handles or expects a `Headers` instance, using methods like `headers.get()` or `headers.set()`.
affects: >=1.4.0
gotcha`ofetch` automatically retries requests if an error occurs and the response status code is within a predefined `retryStatusCodes` list (e.g., 408, 429, 500-503). While beneficial, this can lead to unexpected multiple attempts if not explicitly accounted for.
fix
If automatic retries are undesirable or require fine-tuning, you can configure the `retry` and `retryStatusCodes` options (e.g., `retry: 0` to disable) or use the `onRetry` hook for custom logic.
affects: >=1.0.0
gotcha`ofetch` automatically throws a `FetchError` for non-OK HTTP responses (i.e., `response.ok` is `false`). This differs from the native `fetch` API, which requires manual checking of `response.ok`.
fix
Always wrap `ofetch` calls in a `try...catch` block to handle HTTP errors. Access the error details via `error.data` (if `error` is a `FetchError`) or bypass error throwing with `ignoreResponseError: true` in options.
affects: >=1.0.0
Errors
Common errors & fixes
ReferenceError: require is not defined
Attempting to use CommonJS `require()` in an ES module context, especially with `ofetch` v2.0.0+
fix
Change `const { ofetch } = require('ofetch');` to `import { ofetch } from 'ofetch';` and ensure your project is configured for ES modules.
Property 'data' does not exist on type 'Error'.
Trying to access `error.data` on a generic `Error` object when `ofetch` throws a specific `FetchError`.
fix
Ensure you type-check the error: `if (error instanceof FetchError) { console.error(error.data); }` or explicitly cast the error type if confident.
TypeError: Body stream already read
Attempting to read the response body multiple times or accessing it after it has been consumed (e.g., in a hook without cloning).
fix
If you need to read the response body multiple times within interceptors, clone the response first: `const clonedResponse = response.clone();`.
TypeError: Cannot read properties of undefined (reading 'get')
Interceptors or custom logic are expecting a `Headers` object but receiving a different `HeadersInit` type (like a plain object or array) in versions before v1.4.0 or when not handling normalization correctly.
fix
Ensure your interceptor logic is robust to `Headers` objects and uses methods like `headers.get()`. For pre-1.4.0, manually convert `HeadersInit` to `Headers` if needed for consistent API access.
Upgrade
Version history
1.5.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
4 hits · last 30 days
node
4
Resources