What is ky-universal?
The ky-universal package is a tiny HTTP client based on the Fetch API, designed to work in both Node.js and browser environments. It provides a simple and modern API for making HTTP requests, handling JSON, and dealing with common HTTP tasks.
What are ky-universal's main functionalities?
Simple GET Request
This feature allows you to make a simple GET request to fetch data from a URL. The response is automatically parsed as JSON.
const ky = require('ky-universal');
(async () => {
const json = await ky('https://jsonplaceholder.typicode.com/todos/1').json();
console.log(json);
})();
POST Request with JSON Body
This feature allows you to make a POST request with a JSON body. The response is also parsed as JSON.
const ky = require('ky-universal');
(async () => {
const json = await ky.post('https://jsonplaceholder.typicode.com/posts', {
json: {
title: 'foo',
body: 'bar',
userId: 1
}
}).json();
console.log(json);
})();
Handling Errors
This feature demonstrates how to handle errors when making requests. If the request fails, the error is caught and logged.
const ky = require('ky-universal');
(async () => {
try {
const json = await ky('https://jsonplaceholder.typicode.com/invalid-endpoint').json();
console.log(json);
} catch (error) {
console.log('Error:', error);
}
})();
Retry Mechanism
This feature shows how to use the retry mechanism. If the request fails, it will automatically retry up to the specified number of times.
const ky = require('ky-universal');
(async () => {
const json = await ky('https://jsonplaceholder.typicode.com/todos/1', {
retry: 3
}).json();
console.log(json);
})();
Other packages similar to ky-universal
axios
Axios is a popular HTTP client for both Node.js and the browser. It provides a similar feature set to ky-universal, including support for promises, JSON handling, and error handling. However, Axios has a larger footprint and more configuration options.
node-fetch
Node-fetch is a lightweight module that brings the Fetch API to Node.js. It is similar to ky-universal in that it is based on the Fetch API, but it does not include some of the higher-level features like automatic JSON parsing and retry mechanisms.
superagent
Superagent is a robust HTTP client for Node.js and the browser. It offers a wide range of features, including support for various request types, plugins, and advanced configuration options. It is more feature-rich compared to ky-universal but also more complex.
ky-universal
Use Ky in both Node.js and browsers
Ky is made for browsers, but this package makes it possible to use it in Node.js too, by polyfilling most of the required browser APIs using node-fetch
.
This package can be useful for:
- Isomorphic code
- Web apps (React, Vue.js, etc.) that use server-side rendering (SSR)
- Testing browser libraries using a Node.js test runner
Note: Before opening an issue, make sure it's an issue with Ky and not its polyfills. Generally, if something works in the browser, but not in Node.js, it's an issue with node-fetch
.
Keep in mind that Ky targets modern browsers when used in the browser. For older browsers, you will need to transpile and use a fetch
polyfill.
Install
npm install ky ky-universal
Note that you also need to install ky
.
Usage
import ky from 'ky-universal';
const parsed = await ky('https://httpbin.org/json').json();
ReadableStream
support
For ReadableStream
support, also install web-streams-polyfill
:
$ npm install web-streams-polyfill
You can then use it normally:
import ky from 'ky-universal';
const {body} = await ky('https://httpbin.org/bytes/16');
const {value} = await body.getReader().read();
const result = new TextDecoder('utf-8').decode(value);
API
The API is exactly the same as the Ky API, including the named exports.
FAQ
How do I use this with a web app (React, Vue.js, etc.) that uses server-side rendering (SSR)?
Use it like you would use Ky:
import ky from 'ky-universal';
const parsed = await ky('https://httpbin.org/json').json();
Webpack will ensure the polyfills are only included and used when the app is rendered on the server-side.
How do I test a browser library that uses Ky in AVA?
Put the following in package.json:
{
"ava": {
"require": [
"ky-universal"
]
}
}
The library that uses Ky will now just work in AVA tests.
clone()
hangs with a large response in Node - What should I do?
Streams in Node.js have a smaller internal buffer size (16 kB, aka highWaterMark
) than browsers (>1 MB, not consistent across browsers). When using Ky, the default highWaterMark
is set to 10 MB, so you shouldn't encounter many issues related to that.
However, you can specify a custom highWaterMark
if needed:
import ky from 'ky-universal';
const response = await ky('https://example.com', {
highWaterMark: 1000 * 1000 * 20
});
const data = await response.clone().buffer();
Related
- ky - Tiny and elegant HTTP client based on the browser Fetch API
- got - Simplified HTTP requests in Node.js