Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
ofetch is a modern, lightweight HTTP client for making network requests in JavaScript. It is designed to be simple and easy to use, while providing powerful features for handling HTTP requests and responses.
Basic GET Request
This feature allows you to make a basic GET request to a specified URL and handle the response. The response data is logged to the console.
const { $fetch } = require('ofetch');
(async () => {
const data = await $fetch('https://api.example.com/data');
console.log(data);
})();
POST Request with JSON Body
This feature allows you to make a POST request with a JSON body. The response data is logged to the console.
const { $fetch } = require('ofetch');
(async () => {
const data = await $fetch('https://api.example.com/data', {
method: 'POST',
body: JSON.stringify({ key: 'value' })
});
console.log(data);
})();
Custom Headers
This feature allows you to add custom headers to your HTTP requests. The response data is logged to the console.
const { $fetch } = require('ofetch');
(async () => {
const data = await $fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer token',
'Content-Type': 'application/json'
}
});
console.log(data);
})();
Handling Errors
This feature demonstrates how to handle errors that may occur during an HTTP request. If an error occurs, it is caught and logged to the console.
const { $fetch } = require('ofetch');
(async () => {
try {
const data = await $fetch('https://api.example.com/data');
console.log(data);
} catch (error) {
console.error('Error:', error);
}
})();
Axios is a popular promise-based HTTP client for the browser and Node.js. It provides a rich set of features for making HTTP requests, including support for interceptors, request and response transformation, and automatic JSON parsing. Compared to ofetch, Axios has a larger community and more extensive documentation.
node-fetch is a lightweight module that brings `window.fetch` to Node.js. It is a minimalistic library that provides a simple API for making HTTP requests. While it is similar to ofetch in terms of simplicity, node-fetch is more focused on providing a polyfill for the Fetch API in Node.js environments.
Got is a human-friendly and powerful HTTP request library for Node.js. It supports a wide range of features, including retries, streams, and advanced error handling. Compared to ofetch, Got offers more advanced features and is designed for more complex use cases.
A better fetch API. Works on node, browser and workers.
Install:
# npm
npm i ofetch
# yarn
yarn add ofetch
Import:
// ESM / Typescript
import { ofetch } from "ofetch";
// CommonJS
const { ofetch } = require("ofetch");
We use conditional exports to detect Node.js
and automatically use unjs/node-fetch-native. If globalThis.fetch
is available, will be used instead. To leverage Node.js 17.5.0 experimental native fetch API use --experimental-fetch
flag.
keepAlive
supportBy 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.
ofetch
will smartly parse JSON and native values using destr, falling back to text if it fails to parse.
const { users } = await ofetch("/api/users");
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.
// Use JSON.parse
await ofetch("/movie?lang=en", { parseResponse: JSON.parse });
// 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" });
If an object or a class with a .toJSON()
method is passed to the body
option, ofetch
automatically stringifies it.
ofetch
utilizes JSON.stringify()
to convert the passed object. Classes without a .toJSON()
method have to be converted into a string value in advance before being passed to the body
option.
For PUT
, PATCH
, and POST
request methods, when a string or object body is set, ofetch
adds the default content-type: "application/json"
and accept: "application/json"
headers (which you can always override).
Additionally, ofetch
supports binary responses with Buffer
, ReadableStream
, Stream
, and compatible body types. ofetch will automatically set the duplex: "half"
option for streaming support!
Example:
const { users } = await ofetch("/api/users", {
method: "POST",
body: { some: "json" },
});
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.
await ofetch("https://google.com/404");
// FetchError: [GET] "https://google/404": 404 Not Found
// at async main (/project/playground.ts:4:3)
To catch error response:
await ofetch("/url").catch((err) => err.data);
To bypass status error catching you can set ignoreResponseError
option:
await ofetch("/url", { ignoreResponseError: true });
ofetch
Automatically retries the request if an error happens and if response status code is included in retryStatusCodes
list:
Retry status codes:
408
- Request Timeout409
- Conflict425
- Too Early429
- Too Many Requests500
- Internal Server Error502
- Bad Gateway503
- Service Unavailable504
- Gateway TimeoutYou can specifcy amount of retry and delay between them using retry
and retryDelay
options and also pass a custom array of codes using retryStatusCodes
option.
Default for retry
is 1
retry, except for POST
, PUT
, PATCH
and DELETE
methods where ofetch
does not retry.
Default for retryDelay
is 0
ms.
await ofetch("http://google.com/404", {
retry: 3,
retryDelay: 500, // ms
});
You can specify timeout
in milliseconds to automatically abort request after a timeout (default is disabled).
await ofetch("http://google.com/404", {
timeout: 3000, // Timeout after 3 seconds
});
Response can be type assisted:
const article = await ofetch<Article>(`/api/article/${id}`);
// Auto complete working with article.id
baseURL
By using baseURL
option, ofetch
prepends it with respecting to trailing/leading slashes and query search params for baseURL using ufo:
await ofetch("/config", { baseURL });
By using query
option (or params
as alias), ofetch
adds query search params to URL by preserving query in request itself using ufo:
await ofetch("/movie?lang=en", { query: { id: 123 } });
It is possible to provide async interceptors to hook into lifecycle events of ofetch
call.
You might want to use ofetch.create
to 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.
await ofetch("/api", {
async onRequest({ request, options }) {
// Log request
console.log("[fetch request]", request, options);
// Add `?t=1640125211170` to query search params
options.query = options.query || {};
options.query.t = new Date();
},
});
onRequestError({ request, options, error })
onRequestError
will be called when fetch request fails.
await ofetch("/api", {
async onRequestError({ request, options, error }) {
// Log error
console.log("[fetch request error]", request, error);
},
});
onResponse({ request, options, response })
onResponse
will be called after fetch
call and parsing body.
await ofetch("/api", {
async onResponse({ request, response, options }) {
// Log response
console.log("[fetch response]", request, response.status, response.body);
},
});
onResponseError({ request, options, response })
onResponseError
is same as onResponse
but will be called when fetch happens but response.ok
is not true
.
await ofetch("/api", {
async onResponseError({ request, response, options }) {
// Log error
console.log(
"[fetch response error]",
request,
response.status,
response.body
);
},
});
This utility is useful if you need to use common options across several fetch calls.
Note: Defaults will be cloned at one level and inherited. Be careful about nested options like headers
.
const apiFetch = ofetch.create({ baseURL: "/api" });
apiFetch("/test"); // Same as ofetch('/test', { baseURL: '/api' })
By using headers
option, ofetch
adds extra headers in addition to the request default headers:
await ofetch("/movies", {
headers: {
Accept: "application/json",
"Cache-Control": "no-cache",
},
});
If you need use HTTP(S) Agent, can add agent
option with https-proxy-agent
(for Node.js only):
import { HttpsProxyAgent } from "https-proxy-agent";
await ofetch("/api", {
agent: new HttpsProxyAgent("http://example.com"),
});
If you need to access raw response (for headers, etc), can use ofetch.raw
:
const response = await ofetch.raw("/sushi");
// response._data
// response.headers
// ...
As a shortcut, you can use ofetch.native
that provides native fetch
API
const json = await ofetch.native("/sushi").then((r) => r.json());
ofetch
, destr
and ufo
packages with babel for ES5 supportfetch
global for supporting legacy browsers like using unfetchWhy 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.
MIT. Made with 💖
FAQs
A better fetch API. Works on node, browser and workers.
The npm package ofetch receives a total of 1,147,624 weekly downloads. As such, ofetch popularity was classified as popular.
We found that ofetch demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.