ofetch

repository·main·Indexed 26 days ago

https://github.com/unjs/ofetch

A 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.

Tokens
2.8K
Snippets
9
Records
24
Agent score
89%

What's inside ofetch

  1. Configure proxy support

    main

    Proxy configuration depends on your runtime:

    • Node.js: Use the dispatcher option with undici's ProxyAgent.
    • Bun: Use the proxy option with a string URL.
    • Deno: Supports 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 });
  2. Set request timeout

    main

    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
    });
  3. Configure auto retry logic

    main

    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],
    });
  4. Send JSON request bodies

    main

    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" },
    });
  5. Use baseURL and query parameters

    main

    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.
  6. Access raw response with ofetch.raw

    main

    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.headers
  7. Parse response bodies

    main

    By default, ofetch automatically parses JSON responses. For other content types, you can specify a responseType or provide a custom parseResponse function.

    Supported responseType values:

    • blob
    • arrayBuffer
    • text
    • stream (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" });
  8. Use request interceptors

    main

    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();
      },
    });
  9. Handle request errors

    main
    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.
  10. Configure FetchOptions for ofetch

    main

    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.