ofetch

A better fetch API. Works on node, browser and workers.

README

ofetch


A better fetch API. Works on node, browser and workers.


🚀 Quick Start


Install:

  1. ```bash
  2. # npm
  3. npm i ofetch

  4. # yarn
  5. yarn add ofetch
  6. ```

Import:

  1. ```js
  2. // ESM / Typescript
  3. import { ofetch } from 'ofetch'

  4. // CommonJS
  5. const { ofetch } = require('ofetch')
  6. ```

Spoiler

✔️ Works with Node.js


We use conditional exports to detect Node.js
and automatically use unjs/node-fetch-native. IfglobalThis.fetch is available, will be used instead. To leverage Node.js 17.5.0 experimental native fetch API use [--experimental-fetch flag](https://nodejs.org/dist/latest-v17.x/docs/api/cli.html#--experimental-fetch).

keepAlive support


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 reestablish a TCP connection.

Note: This option can potentially introduce memory leaks. Please check node-fetch/node-fetch#1325.

✔️ Parsing Response


ofetch will smartly parse JSON and native values using destr, falling back to text if it fails to parse.

  1. ```js
  2. const { users } = await ofetch('/api/users')
  3. ```

For binary content types, ofetch will instead return a Blob object.

You can optionally provide a different parser than destr, or specify blob, arrayBuffer or text to force parsing the body with the respective FetchResponse method.

  1. ```js
  2. // Use JSON.parse
  3. await ofetch('/movie?lang=en', { parseResponse: JSON.parse })

  4. // Return text as is
  5. await ofetch('/movie?lang=en', { parseResponse: txt => txt })

  6. // Get the blob version of the response
  7. await ofetch('/api/generate-image', { responseType: 'blob' })
  8. ```

✔️ JSON Body


ofetch automatically stringifies request body (if an object is passed) and adds JSON Content-Type and Accept headers (for put, patch and post requests).

  1. ```js
  2. const { users } = await ofetch('/api/users', { method: 'POST', body: { some: 'json' } })
  3. ```

✔️ Handling Errors


ofetch Automatically throw errors when response.ok is false with a friendly error message and compact stack (hiding internals).

Parsed error body is available with error.data. You may also use FetchError type.

  1. ```ts
  2. await ofetch('http://google.com/404')
  3. // FetchError: 404 Not Found (http://google.com/404)
  4. //     at async main (/project/playground.ts:4:3)
  5. ```

In order to bypass errors as response you can use error.data:

  1. ```ts
  2. await ofetch(...).catch((error) => error.data)
  3. ```

✔️ Auto Retry


ofetch Automatically retries the request if an error happens. Default is 1 (except for POST, PUT and PATCH methods that is 0)

  1. ```ts
  2. await ofetch('http://google.com/404', {
  3.   retry: 3
  4. })
  5. ```

✔️ Type Friendly


Response can be type assisted:

  1. ```ts
  2. const article = await ofetch<Article>(`/api/article/${id}`)
  3. // Auto complete working with article.id
  4. ```

✔️ Adding baseURL


By using baseURL option, ofetch prepends it with respecting to trailing/leading slashes and query search params for baseURL using ufo:

  1. ```js
  2. await ofetch('/config', { baseURL })
  3. ```

✔️ Adding Query Search Params


By using query option (or params as alias), ofetch adds query search params to URL by preserving query in request itself using ufo:

  1. ```js
  2. await ofetch('/movie?lang=en', { query: { id: 123 } })
  3. ```

✔️ Interceptors


It is possible to provide async interceptors to hook into lifecycle events of ofetch call.

You might want to use ofetch.create to set set shared interceptors.

onRequest({ request, options })


onRequest is called as soon as ofetch is being called, allowing to modify options or just do simple logging.

  1. ```js
  2. await ofetch('/api', {
  3.   async onRequest({ request, options }) {
  4.     // Log request
  5.     console.log('[fetch request]', request, options)

  6.     // Add `?t=1640125211170` to query search params
  7.     options.query = options.query || {}
  8.     options.query.t = new Date()
  9.   }
  10. })
  11. ```

onRequestError({ request, options, error })


onRequestError will be called when fetch request fails.

  1. ```js
  2. await ofetch('/api', {
  3.   async onRequestError({ request, options, error }) {
  4.     // Log error
  5.     console.log('[fetch request error]', request, error)
  6.   }
  7. })
  8. ```


onResponse({ request, options, response })


onResponse will be called after fetch call and parsing body.

  1. ```js
  2. await ofetch('/api', {
  3.   async onResponse({ request, response, options }) {
  4.     // Log response
  5.     console.log('[fetch response]', request, response.status, response.body)
  6.   }
  7. })
  8. ```

onResponseError({ request, options, response })


onResponseError is same as onResponse but will be called when fetch happens but response.ok is not true.

  1. ```js
  2. await ofetch('/api', {
  3.   async onResponseError({ request, response, options }) {
  4.     // Log error
  5.     console.log('[fetch response error]', request, response.status, response.body)
  6.   }
  7. })
  8. ```

✔️ Create fetch with default options


This utility is useful if you need to use common options across serveral fetch calls.

Note: Defaults will be cloned at one level and inherrited. Be careful about nested options like headers.

  1. ```js
  2. const apiFetch = ofetch.create({ baseURL: '/api' })

  3. apiFetch('/test') // Same as ofetch('/test', { baseURL: '/api' })
  4. ```

💡 Adding headers


By using headers option, ofetch adds extra headers in addition to the request default headers:

  1. ```js
  2. await ofetch('/movies', {
  3.   headers: {
  4.     Accept: 'application/json',
  5.     'Cache-Control': 'no-cache'
  6.   }
  7. })
  8. ```

🍣 Access to Raw Response


If you need to access raw response (for headers, etc), can use ofetch.raw:

  1. ```js
  2. const response = await ofetch.raw('/sushi')

  3. // response.data
  4. // response.headers
  5. // ...
  6. ```

Native fetch


As a shortcut, you can use ofetch.native that provides native fetch API

  1. ```js
  2. const json = await ofetch.native('/sushi').then(r => r.json())
  3. ```

📦 Bundler Notes


- All targets are exported with Module and CommonJS format and named exports
- No export is transpiled for 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 closest possible alternative. You can however, import { fetch } from ofetch which is auto polyfilled for Node.js and using native otherwise.

Why not having 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 keep transpiling libraries we push 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.

License


MIT. Made with 💖