Universal HTTP fetch library with intelligent parsing, error handling, retry logic, and cross-environment compatibility
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Primary fetch functionality with enhanced features including automatic JSON parsing, intelligent error handling, cross-environment compatibility, and response type management.
The primary ofetch function that provides enhanced fetch capabilities with automatic response parsing and error handling.
/**
* Enhanced fetch function with automatic response parsing
* @param request - URL string or Request object
* @param options - Fetch configuration options
* @returns Promise resolving to parsed response data
*/
function ofetch<T = any, R extends ResponseType = "json">(
request: FetchRequest,
options?: FetchOptions<R>
): Promise<MappedResponseType<R, T>>;
// Alias for ofetch
const $fetch: typeof ofetch;Usage Examples:
import { ofetch } from "ofetch";
// Simple GET request with automatic JSON parsing
const users = await ofetch("https://api.example.com/users");
// GET with query parameters
const filtered = await ofetch("https://api.example.com/users", {
query: { active: true, limit: 10 }
});
// POST with JSON body
const newUser = await ofetch("https://api.example.com/users", {
method: "POST",
body: { name: "Alice", email: "alice@example.com" }
});
// Custom response type
const imageBlob = await ofetch("https://api.example.com/image.png", {
responseType: "blob"
});
// With type safety
interface User {
id: number;
name: string;
email: string;
}
const user = await ofetch<User>("https://api.example.com/users/1");Access the full Response object with parsed data attached, useful for accessing headers, status codes, and other response metadata.
/**
* Fetch with access to full Response object
* @param request - URL string or Request object
* @param options - Fetch configuration options
* @returns Promise resolving to Response object with _data property
*/
function raw<T = any, R extends ResponseType = "json">(
request: FetchRequest,
options?: FetchOptions<R>
): Promise<FetchResponse<MappedResponseType<R, T>>>;Usage Examples:
import { ofetch } from "ofetch";
// Access response headers and status
const response = await ofetch.raw("https://api.example.com/users");
console.log(response.status); // 200
console.log(response.headers.get("content-type"));
console.log(response._data); // Parsed response data
// Handle different status codes
const response = await ofetch.raw("https://api.example.com/users/999", {
ignoreResponseError: true
});
if (response.status === 404) {
console.log("User not found");
} else {
console.log(response._data);
}Direct access to the underlying native fetch API for cases requiring standard fetch behavior.
/**
* Access to native fetch API
* @param args - Standard fetch arguments
* @returns Promise resolving to standard Response object
*/
native(...args: Parameters<typeof globalThis.fetch>): Promise<Response>;Usage Examples:
import { ofetch } from "ofetch";
// Use native fetch for streaming or custom handling
const response = await ofetch.native("https://api.example.com/stream");
const reader = response.body?.getReader();
// Standard fetch behavior without ofetch enhancements
const response = await ofetch.native("https://api.example.com/data", {
method: "POST",
body: JSON.stringify({ key: "value" }),
headers: { "Content-Type": "application/json" }
});
const data = await response.json();Create customized fetch instances with default options, base URLs, and configuration that applies to all requests made with that instance.
/**
* Create a customized fetch instance with default options
* @param defaults - Default options to apply to all requests
* @param globalOptions - Global configuration for the instance
* @returns New $Fetch instance with applied defaults
*/
function create(
defaults?: FetchOptions,
globalOptions?: CreateFetchOptions
): $Fetch;Usage Examples:
import { ofetch } from "ofetch";
// Create API client with base URL and auth
const api = ofetch.create({
baseURL: "https://api.example.com",
headers: {
"Authorization": "Bearer token123",
"Content-Type": "application/json"
},
timeout: 5000
});
// Use the configured instance
const users = await api("/users"); // GET https://api.example.com/users
const user = await api("/users/1"); // GET https://api.example.com/users/1
// Override defaults per request
const adminUsers = await api("/admin/users", {
headers: { "X-Admin": "true" }
});
// Create instance with custom fetch implementation
const customFetch = ofetch.create({
baseURL: "https://internal.api.com"
}, {
fetch: globalThis.fetch,
Headers: globalThis.Headers
});Configure how responses are parsed based on content type or explicit specification.
type ResponseType = "json" | "text" | "blob" | "arrayBuffer" | "stream";
type MappedResponseType<R extends ResponseType, JsonType = any> =
R extends keyof ResponseMap ? ResponseMap[R] : JsonType;
interface ResponseMap {
blob: Blob;
text: string;
arrayBuffer: ArrayBuffer;
stream: ReadableStream<Uint8Array>;
}Usage Examples:
import { ofetch } from "ofetch";
// Automatic JSON parsing (default)
const data = await ofetch("https://api.example.com/data.json");
// Force text parsing
const text = await ofetch("https://api.example.com/document", {
responseType: "text"
});
// Get binary data as blob
const image = await ofetch("https://api.example.com/image.png", {
responseType: "blob"
});
// Get raw bytes as ArrayBuffer
const buffer = await ofetch("https://api.example.com/file.bin", {
responseType: "arrayBuffer"
});
// Get streaming response
const stream = await ofetch("https://api.example.com/large-file", {
responseType: "stream"
});
// Custom response parser
const data = await ofetch("https://api.example.com/custom", {
parseResponse: (text) => text.split("\\n").map(line => line.trim())
});// Universal exports (from "ofetch")
// Automatically uses Node.js optimizations when in Node.js environment
export const ofetch: $Fetch;
export const $fetch: $Fetch;
export const fetch: typeof globalThis.fetch;
export const Headers: typeof globalThis.Headers;
export const AbortController: typeof globalThis.AbortController;
export function createFetch(globalOptions?: CreateFetchOptions): $Fetch;
export class FetchError<T = any> extends Error implements IFetchError<T> {}
export function createFetchError<T = any>(ctx: FetchContext<T>): IFetchError<T>;
// Node.js specific exports (from "ofetch/node")
// Same API as main export, but with explicit Node.js optimizations
export const ofetch: $Fetch;
export const $fetch: $Fetch;
export const fetch: typeof globalThis.fetch; // With conditional keep-alive support
export const Headers: typeof globalThis.Headers;
export const AbortController: typeof globalThis.AbortController;
export function createFetch(globalOptions?: CreateFetchOptions): $Fetch;
export function createNodeFetch(): typeof globalThis.fetch;
export class FetchError<T = any> extends Error implements IFetchError<T> {}
export function createFetchError<T = any>(ctx: FetchContext<T>): IFetchError<T>;
// Utilities (from "ofetch")
export function isPayloadMethod(method?: string): boolean;
export function isJSONSerializable(value: any): boolean;
export function detectResponseType(contentType?: string): ResponseType;
export function resolveFetchOptions<R extends ResponseType, T>(
request: FetchRequest,
input: FetchOptions<R, T> | undefined,
defaults: FetchOptions<R, T> | undefined,
Headers: typeof globalThis.Headers
): ResolvedFetchOptions<R, T>;
export function callHooks<C extends FetchContext>(
context: C,
hooks: FetchHook<C> | FetchHook<C>[] | undefined
): Promise<void>;Install with Tessl CLI
npx tessl i tessl/npm-ofetch