Top Related Projects
Promise based HTTP client for the browser and node.js
A light-weight module that brings the Fetch API to Node.js
The all-batteries-included GitHub SDK for Browsers, Node.js, and Deno.
Ajax for Node.js and browsers (JS HTTP client). Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.
🏊🏾 Simplified HTTP request client.
A window.fetch JavaScript polyfill.
Quick Overview
Ky is a tiny and elegant HTTP client based on the browser Fetch API. It provides a simpler interface for making HTTP requests with additional features like retries, timeouts, and hooks. Ky is designed to be lightweight and easy to use, making it an excellent choice for both browser and Node.js environments.
Pros
- Lightweight and minimal, with a small bundle size
- Built on top of the Fetch API, providing a familiar and standardized foundation
- Supports both browser and Node.js environments
- Offers useful features like automatic retries, timeouts, and hooks
Cons
- Limited browser support compared to more established libraries like Axios
- Lacks some advanced features found in larger HTTP client libraries
- May require additional polyfills for older browsers
- Not as widely adopted as some other HTTP client libraries
Code Examples
- Basic GET request:
import ky from 'ky';
const json = await ky.get('https://api.example.com/data').json();
console.log(json);
- POST request with JSON payload:
import ky from 'ky';
const response = await ky.post('https://api.example.com/users', {
json: { name: 'John Doe', email: 'john@example.com' }
}).json();
console.log(response);
- Using hooks and retries:
import ky from 'ky';
const api = ky.extend({
hooks: {
beforeRequest: [
request => {
request.headers.set('X-API-Key', 'my-api-key');
}
]
},
retry: 3
});
const response = await api.get('https://api.example.com/data').json();
console.log(response);
Getting Started
To use Ky in your project, first install it via npm:
npm install ky
Then, import and use it in your JavaScript code:
import ky from 'ky';
// Make a GET request
const json = await ky.get('https://api.example.com/data').json();
// Make a POST request
const response = await ky.post('https://api.example.com/users', {
json: { name: 'John Doe', email: 'john@example.com' }
}).json();
// Use with custom options
const api = ky.extend({
prefixUrl: 'https://api.example.com',
timeout: 5000,
retry: 3
});
const result = await api.get('endpoint').json();
Competitor Comparisons
Promise based HTTP client for the browser and node.js
Pros of Axios
- Supports older browsers (IE11+) and Node.js environments
- More extensive feature set, including request cancellation and automatic request retries
- Larger ecosystem with more plugins and integrations
Cons of Axios
- Larger bundle size, which may impact performance in browser environments
- More complex API with a steeper learning curve
- Less modern syntax and features compared to Ky
Code Comparison
Axios:
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
Ky:
ky.get('https://api.example.com/data')
.json()
.then(data => console.log(data))
.catch(error => console.error(error));
Summary
Axios is a more established and feature-rich HTTP client with broader browser support and a larger ecosystem. It's suitable for complex applications and those requiring legacy browser compatibility. Ky, on the other hand, is a modern, lightweight alternative that leverages the Fetch API, offering a simpler interface and smaller bundle size. It's ideal for projects targeting modern browsers and prioritizing performance. The choice between the two depends on specific project requirements, target environments, and developer preferences.
A light-weight module that brings the Fetch API to Node.js
Pros of node-fetch
- Closer to the native Fetch API, making it easier for developers familiar with browser-based fetch
- Lightweight and focused solely on providing fetch functionality
- Well-established and widely used in the Node.js ecosystem
Cons of node-fetch
- Less feature-rich compared to ky, which offers additional convenience methods
- Doesn't provide built-in request retrying or timeout functionality
- Requires more manual configuration for advanced use cases
Code Comparison
node-fetch:
const fetch = require('node-fetch');
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
ky:
const ky = require('ky-universal');
ky.get('https://api.example.com/data')
.json()
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
The code comparison shows that ky provides a more concise syntax for common operations like parsing JSON responses. It also offers method chaining for improved readability. However, node-fetch's approach is closer to the native Fetch API, which may be preferable for developers seeking consistency with browser-based fetch implementations.
The all-batteries-included GitHub SDK for Browsers, Node.js, and Deno.
Pros of Octokit.js
- Specifically designed for GitHub API interactions
- Comprehensive coverage of GitHub API endpoints
- Built-in authentication and pagination handling
Cons of Octokit.js
- Larger package size due to its comprehensive nature
- Steeper learning curve for simple API requests
- Limited to GitHub-specific use cases
Code Comparison
Octokit.js:
const octokit = new Octokit({ auth: 'token' });
const { data } = await octokit.rest.repos.get({
owner: 'octokit',
repo: 'octokit.js'
});
Ky:
import ky from 'ky';
const data = await ky.get('https://api.github.com/repos/sindresorhus/ky').json();
Summary
Octokit.js is a powerful and comprehensive library specifically designed for interacting with the GitHub API. It offers built-in authentication, pagination handling, and covers all GitHub API endpoints. However, its large package size and GitHub-specific focus may be overkill for simple API requests.
Ky, on the other hand, is a lightweight and versatile HTTP client that can be used for various API interactions, including GitHub. It has a smaller footprint and a simpler API, making it easier to use for basic requests. However, it lacks the GitHub-specific features and comprehensive API coverage that Octokit.js provides.
Choose Octokit.js for extensive GitHub API interactions and Ky for simpler, more general-purpose HTTP requests.
Ajax for Node.js and browsers (JS HTTP client). Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.
Pros of Superagent
- More mature and established library with a longer history
- Supports both Node.js and browser environments
- Offers a wider range of features and plugins
Cons of Superagent
- Larger bundle size compared to Ky
- Less modern API design, not utilizing Promises as extensively
- Slower development and release cycle
Code Comparison
Superagent:
superagent
.post('/api/pet')
.send({ name: 'Manny', species: 'cat' })
.set('X-API-Key', 'foobar')
.set('Accept', 'application/json')
.end((err, res) => {
// Callback
});
Ky:
await ky.post('/api/pet', {
json: { name: 'Manny', species: 'cat' },
headers: {
'X-API-Key': 'foobar',
'Accept': 'application/json'
}
}).json();
Ky offers a more modern, Promise-based API with a cleaner syntax. Superagent uses a chaining approach with a callback, which can lead to callback hell in more complex scenarios. Ky's API is more concise and easier to read, especially when used with async/await. However, Superagent's API might be more familiar to developers accustomed to older JavaScript patterns.
🏊🏾 Simplified HTTP request client.
Pros of Request
- Mature and well-established library with a large ecosystem of plugins
- Supports both Node.js and browser environments
- Extensive documentation and community support
Cons of Request
- No longer actively maintained (deprecated)
- Larger bundle size compared to more modern alternatives
- Callback-based API, which can lead to callback hell in complex scenarios
Code Comparison
Request:
request('https://api.example.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
Ky:
import ky from 'ky';
const json = await ky.get('https://api.example.com').json();
console.log(json);
Key Differences
- Ky is a modern, lightweight alternative to Request
- Ky uses Promises and async/await syntax, making it more readable and easier to work with
- Ky is actively maintained and designed for modern JavaScript environments
- Request has a larger feature set out-of-the-box, while Ky focuses on simplicity and performance
- Ky is smaller in size and has better tree-shaking support for reduced bundle sizes
Overall, while Request has been a popular choice for many years, Ky offers a more modern and efficient approach to making HTTP requests in JavaScript applications.
A window.fetch JavaScript polyfill.
Pros of fetch
- Lightweight and simple, with a smaller bundle size
- Closer to the native Fetch API, requiring less learning for developers familiar with standard JavaScript
- No external dependencies, potentially reducing security risks
Cons of fetch
- Fewer built-in features and conveniences compared to ky
- Less comprehensive error handling and request/response interception capabilities
- May require more manual configuration for common use cases
Code Comparison
fetch:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
ky:
import ky from 'ky';
ky.get('https://api.example.com/data')
.json()
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
The fetch example shows a more basic approach, while ky demonstrates its simplified API with method chaining and built-in JSON parsing. ky offers a more concise syntax for common operations, but fetch provides a lower-level interface that may be preferred for certain use cases or when minimizing dependencies is a priority.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Sindre's open source work is supported by the community.
Special thanks to:
Ky is a tiny and elegant HTTP client based on the Fetch API
Ky targets modern browsers, Node.js, Bun, and Deno.
It's just a tiny package with no dependencies.
Benefits over plain fetch
- Simpler API
- Method shortcuts (
ky.post()
) - Treats non-2xx status codes as errors (after redirects)
- Retries failed requests
- JSON option
- Timeout support
- URL prefix option
- Instances with custom defaults
- Hooks
- TypeScript niceties (e.g.
.json()
supports generics and defaults tounknown
, notany
)
Install
npm install ky
CDN
Usage
import ky from 'ky';
const json = await ky.post('https://example.com', {json: {foo: true}}).json();
console.log(json);
//=> `{data: 'ð¦'}`
With plain fetch
, it would be:
class HTTPError extends Error {}
const response = await fetch('https://example.com', {
method: 'POST',
body: JSON.stringify({foo: true}),
headers: {
'content-type': 'application/json'
}
});
if (!response.ok) {
throw new HTTPError(`Fetch error: ${response.statusText}`);
}
const json = await response.json();
console.log(json);
//=> `{data: 'ð¦'}`
If you are using Deno, import Ky from a URL. For example, using a CDN:
import ky from 'https://esm.sh/ky';
API
ky(input, options?)
The input
and options
are the same as fetch
, with additional options
available (see below).
Returns a Response
object with Body
methods added for convenience. So you can, for example, call ky.get(input).json()
directly without having to await the Response
first. When called like that, an appropriate Accept
header will be set depending on the body method used. Unlike the Body
methods of window.Fetch
; these will throw an HTTPError
if the response status is not in the range of 200...299
. Also, .json()
will return an empty string if body is empty or the response status is 204
instead of throwing a parse error due to an empty body.
import ky from 'ky';
const user = await ky('/api/user').json();
console.log(user);
â¨ï¸ TypeScript: Accepts an optional type parameter, which defaults to unknown
, and is passed through to the return type of .json()
.
import ky from 'ky';
// user1 is unknown
const user1 = await ky('/api/users/1').json();
// user2 is a User
const user2 = await ky<User>('/api/users/2').json();
// user3 is a User
const user3 = await ky('/api/users/3').json<User>();
console.log([user1, user2, user3]);
ky.get(input, options?)
ky.post(input, options?)
ky.put(input, options?)
ky.patch(input, options?)
ky.head(input, options?)
ky.delete(input, options?)
Sets options.method
to the method name and makes a request.
â¨ï¸ TypeScript: Accepts an optional type parameter for use with JSON responses (see ky()
).
input
Type: string
| URL
| Request
Same as fetch
input.
When using a Request
instance as input
, any URL altering options (such as prefixUrl
) will be ignored.
options
Type: object
Same as fetch
options, plus the following additional options:
method
Type: string
Default: 'get'
HTTP method used to make the request.
Internally, the standard methods (GET
, POST
, PUT
, PATCH
, HEAD
and DELETE
) are uppercased in order to avoid server errors due to case sensitivity.
json
Type: object
and any other value accepted by JSON.stringify()
Shortcut for sending JSON. Use this instead of the body
option. Accepts any plain object or value, which will be JSON.stringify()
'd and sent in the body with the correct header set.
searchParams
Type: string | object<string, string | number | boolean> | Array<Array<string | number | boolean>> | URLSearchParams
Default: ''
Search parameters to include in the request URL. Setting this will override all existing search parameters in the input URL.
Accepts any value supported by URLSearchParams()
.
prefixUrl
Type: string | URL
A prefix to prepend to the input
URL when making the request. It can be any valid URL, either relative or absolute. A trailing slash /
is optional and will be added automatically, if needed, when it is joined with input
. Only takes effect when input
is a string. The input
argument cannot start with a slash /
when using this option.
Useful when used with ky.extend()
to create niche-specific Ky-instances.
import ky from 'ky';
// On https://example.com
const response = await ky('unicorn', {prefixUrl: '/api'});
//=> 'https://example.com/api/unicorn'
const response2 = await ky('unicorn', {prefixUrl: 'https://cats.com'});
//=> 'https://cats.com/unicorn'
Notes:
- After
prefixUrl
andinput
are joined, the result is resolved against the base URL of the page (if any). - Leading slashes in
input
are disallowed when using this option to enforce consistency and avoid confusion about how theinput
URL is handled, given thatinput
will not follow the normal URL resolution rules whenprefixUrl
is being used, which changes the meaning of a leading slash.
retry
Type: object | number
Default:
limit
:2
methods
:get
put
head
delete
options
trace
statusCodes
:408
413
429
500
502
503
504
afterStatusCodes
:413
,429
,503
maxRetryAfter
:undefined
backoffLimit
:undefined
delay
:attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000
An object representing limit
, methods
, statusCodes
, afterStatusCodes
, and maxRetryAfter
fields for maximum retry count, allowed methods, allowed status codes, status codes allowed to use the Retry-After
time, and maximum Retry-After
time.
If retry
is a number, it will be used as limit
and other defaults will remain in place.
If the response provides an HTTP status contained in afterStatusCodes
, Ky will wait until the date, timeout, or timestamp given in the Retry-After
header has passed to retry the request. If Retry-After
is missing, the non-standard RateLimit-Reset
header is used in its place as a fallback. If the provided status code is not in the list, the Retry-After
header will be ignored.
If maxRetryAfter
is set to undefined
, it will use options.timeout
. If Retry-After
header is greater than maxRetryAfter
, it will use maxRetryAfter
.
The backoffLimit
option is the upper limit of the delay per retry in milliseconds.
To clamp the delay, set backoffLimit
to 1000, for example.
By default, the delay is calculated with 0.3 * (2 ** (attemptCount - 1)) * 1000
. The delay increases exponentially.
The delay
option can be used to change how the delay between retries is calculated. The function receives one parameter, the attempt count, starting at 1
.
Retries are not triggered following a timeout.
import ky from 'ky';
const json = await ky('https://example.com', {
retry: {
limit: 10,
methods: ['get'],
statusCodes: [413],
backoffLimit: 3000
}
}).json();
timeout
Type: number | false
Default: 10000
Timeout in milliseconds for getting a response, including any retries. Can not be greater than 2147483647.
If set to false
, there will be no timeout.
hooks
Type: object<string, Function[]>
Default: {beforeRequest: [], beforeRetry: [], afterResponse: []}
Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially.
hooks.beforeRequest
Type: Function[]
Default: []
This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives request
and options
as arguments. You could, for example, modify the request.headers
here.
The hook can return a Request
to replace the outgoing request, or return a Response
to completely avoid making an HTTP request. This can be used to mock a request, check an internal cache, etc. An important consideration when returning a request or response from this hook is that any remaining beforeRequest
hooks will be skipped, so you may want to only return them from the last hook.
import ky from 'ky';
const api = ky.extend({
hooks: {
beforeRequest: [
request => {
request.headers.set('X-Requested-With', 'ky');
}
]
}
});
const response = await api.get('https://example.com/api/users');
hooks.beforeRetry
Type: Function[]
Default: []
This hook enables you to modify the request right before retry. Ky will make no further changes to the request after this. The hook function receives an object with the normalized request and options, an error instance, and the retry count. You could, for example, modify request.headers
here.
If the request received a response, the error will be of type HTTPError
and the Response
object will be available at error.response
. Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will not be an instance of HTTPError
.
You can prevent Ky from retrying the request by throwing an error. Ky will not handle it in any way and the error will be propagated to the request initiator. The rest of the beforeRetry
hooks will not be called in this case. Alternatively, you can return the ky.stop
symbol to do the same thing but without propagating an error (this has some limitations, see ky.stop
docs for details).
import ky from 'ky';
const response = await ky('https://example.com', {
hooks: {
beforeRetry: [
async ({request, options, error, retryCount}) => {
const token = await ky('https://example.com/refresh-token');
request.headers.set('Authorization', `token ${token}`);
}
]
}
});
hooks.beforeError
Type: Function[]
Default: []
This hook enables you to modify the HTTPError
right before it is thrown. The hook function receives a HTTPError
as an argument and should return an instance of HTTPError
.
import ky from 'ky';
await ky('https://example.com', {
hooks: {
beforeError: [
error => {
const {response} = error;
if (response && response.body) {
error.name = 'GitHubError';
error.message = `${response.body.message} (${response.status})`;
}
return error;
}
]
}
});
hooks.afterResponse
Type: Function[]
Default: []
This hook enables you to read and optionally modify the response. The hook function receives normalized request, options, and a clone of the response as arguments. The return value of the hook function will be used by Ky as the response object if it's an instance of Response
.
import ky from 'ky';
const response = await ky('https://example.com', {
hooks: {
afterResponse: [
(_request, _options, response) => {
// You could do something with the response, for example, logging.
log(response);
// Or return a `Response` instance to overwrite the response.
return new Response('A different response', {status: 200});
},
// Or retry with a fresh token on a 403 error
async (request, options, response) => {
if (response.status === 403) {
// Get a fresh token
const token = await ky('https://example.com/token').text();
// Retry with the token
request.headers.set('Authorization', `token ${token}`);
return ky(request);
}
}
]
}
});
throwHttpErrors
Type: boolean
Default: true
Throw an HTTPError
when, after following redirects, the response has a non-2xx status code. To also throw for redirects instead of following them, set the redirect
option to 'manual'
.
Setting this to false
may be useful if you are checking for resource availability and are expecting error responses.
Note: If false
, error responses are considered successful and the request will not be retried.
onDownloadProgress
Type: Function
Download progress event handler.
The function receives a progress
and chunk
argument:
- The
progress
object contains the following elements:percent
,transferredBytes
andtotalBytes
. If it's not possible to retrieve the body size,totalBytes
will be0
. - The
chunk
argument is an instance ofUint8Array
. It's empty for the first call.
import ky from 'ky';
const response = await ky('https://example.com', {
onDownloadProgress: (progress, chunk) => {
// Example output:
// `0% - 0 of 1271 bytes`
// `100% - 1271 of 1271 bytes`
console.log(`${progress.percent * 100}% - ${progress.transferredBytes} of ${progress.totalBytes} bytes`);
}
});
parseJson
Type: Function
Default: JSON.parse()
User-defined JSON-parsing function.
Use-cases:
- Parse JSON via the
bourne
package to protect from prototype pollution. - Parse JSON with
reviver
option ofJSON.parse()
.
import ky from 'ky';
import bourne from '@hapijs/bourne';
const json = await ky('https://example.com', {
parseJson: text => bourne(text)
}).json();
stringifyJson
Type: Function
Default: JSON.stringify()
User-defined JSON-stringifying function.
Use-cases:
- Stringify JSON with a custom
replacer
function.
import ky from 'ky';
import {DateTime} from 'luxon';
const json = await ky('https://example.com', {
stringifyJson: data => JSON.stringify(data, (key, value) => {
if (key.endsWith('_at')) {
return DateTime.fromISO(value).toSeconds();
}
return value;
})
}).json();
fetch
Type: Function
Default: fetch
User-defined fetch
function.
Has to be fully compatible with the Fetch API standard.
Use-cases:
- Use custom
fetch
implementations likeisomorphic-unfetch
. - Use the
fetch
wrapper function provided by some frameworks that use server-side rendering (SSR).
import ky from 'ky';
import fetch from 'isomorphic-unfetch';
const json = await ky('https://example.com', {fetch}).json();
ky.extend(defaultOptions)
Create a new ky
instance with some defaults overridden with your own.
In contrast to ky.create()
, ky.extend()
inherits defaults from its parent.
You can pass headers as a Headers
instance or a plain object.
You can remove a header with .extend()
by passing the header with an undefined
value.
Passing undefined
as a string removes the header only if it comes from a Headers
instance.
Similarly, you can remove existing hooks
entries by extending the hook with an explicit undefined
.
import ky from 'ky';
const url = 'https://sindresorhus.com';
const original = ky.create({
headers: {
rainbow: 'rainbow',
unicorn: 'unicorn'
},
hooks: {
beforeRequest: [ () => console.log('before 1') ],
afterResponse: [ () => console.log('after 1') ],
},
});
const extended = original.extend({
headers: {
rainbow: undefined
},
hooks: {
beforeRequest: undefined,
afterResponse: [ () => console.log('after 2') ],
}
});
const response = await extended(url).json();
//=> after 1
//=> after 2
console.log('rainbow' in response);
//=> false
console.log('unicorn' in response);
//=> true
You can also refer to parent defaults by providing a function to .extend()
.
import ky from 'ky';
const api = ky.create({prefixUrl: 'https://example.com/api'});
const usersApi = api.extend((options) => ({prefixUrl: `${options.prefixUrl}/users`}));
const response = await usersApi.get('123');
//=> 'https://example.com/api/users/123'
const response = await api.get('version');
//=> 'https://example.com/api/version'
ky.create(defaultOptions)
Create a new Ky instance with complete new defaults.
import ky from 'ky';
// On https://my-site.com
const api = ky.create({prefixUrl: 'https://example.com/api'});
const response = await api.get('users/123');
//=> 'https://example.com/api/users/123'
const response = await api.get('/status', {prefixUrl: ''});
//=> 'https://my-site.com/status'
defaultOptions
Type: object
ky.stop
A Symbol
that can be returned by a beforeRetry
hook to stop the retry. This will also short circuit the remaining beforeRetry
hooks.
Note: Returning this symbol makes Ky abort and return with an undefined
response. Be sure to check for a response before accessing any properties on it or use optional chaining. It is also incompatible with body methods, such as .json()
or .text()
, because there is no response to parse. In general, we recommend throwing an error instead of returning this symbol, as that will cause Ky to abort and then throw, which avoids these limitations.
A valid use-case for ky.stop
is to prevent retries when making requests for side effects, where the returned data is not important. For example, logging client activity to the server.
import ky from 'ky';
const options = {
hooks: {
beforeRetry: [
async ({request, options, error, retryCount}) => {
const shouldStopRetry = await ky('https://example.com/api');
if (shouldStopRetry) {
return ky.stop;
}
}
]
}
};
// Note that response will be `undefined` in case `ky.stop` is returned.
const response = await ky.post('https://example.com', options);
// Using `.text()` or other body methods is not supported.
const text = await ky('https://example.com', options).text();
HTTPError
Exposed for instanceof
checks. The error has a response
property with the Response
object, request
property with the Request
object, and options
property with normalized options (either passed to ky
when creating an instance with ky.create()
or directly when performing the request).
If you need to read the actual response when an HTTPError
has occurred, call the respective parser method on the response object. For example:
try {
await ky('https://example.com').json();
} catch (error) {
if (error.name === 'HTTPError') {
const errorJson = await error.response.json();
}
}
â¨ï¸ TypeScript: Accepts an optional type parameter, which defaults to unknown
, and is passed through to the return type of error.response.json()
.
TimeoutError
The error thrown when the request times out. It has a request
property with the Request
object.
Tips
Sending form data
Sending form data in Ky is identical to fetch
. Just pass a FormData
instance to the body
option. The Content-Type
header will be automatically set to multipart/form-data
.
import ky from 'ky';
// `multipart/form-data`
const formData = new FormData();
formData.append('food', 'fries');
formData.append('drink', 'icetea');
const response = await ky.post(url, {body: formData});
If you want to send the data in application/x-www-form-urlencoded
format, you will need to encode the data with URLSearchParams
.
import ky from 'ky';
// `application/x-www-form-urlencoded`
const searchParams = new URLSearchParams();
searchParams.set('food', 'fries');
searchParams.set('drink', 'icetea');
const response = await ky.post(url, {body: searchParams});
Setting a custom Content-Type
Ky automatically sets an appropriate Content-Type
header for each request based on the data in the request body. However, some APIs require custom, non-standard content types, such as application/x-amz-json-1.1
. Using the headers
option, you can manually override the content type.
import ky from 'ky';
const json = await ky.post('https://example.com', {
headers: {
'content-type': 'application/json'
},
json: {
foo: true
},
}).json();
console.log(json);
//=> `{data: 'ð¦'}`
Cancellation
Fetch (and hence Ky) has built-in support for request cancellation through the AbortController
API. Read more.
Example:
import ky from 'ky';
const controller = new AbortController();
const {signal} = controller;
setTimeout(() => {
controller.abort();
}, 5000);
try {
console.log(await ky(url, {signal}).text());
} catch (error) {
if (error.name === 'AbortError') {
console.log('Fetch aborted');
} else {
console.error('Fetch error:', error);
}
}
FAQ
How do I use this in Node.js?
Node.js 18 and later supports fetch
natively, so you can just use this package directly.
How do I use this with a web app (React, Vue.js, etc.) that uses server-side rendering (SSR)?
Same as above.
How do I test a browser library that uses this?
Either use a test runner that can run in the browser, like Mocha, or use AVA with ky-universal
. Read more.
How do I use this without a bundler like Webpack?
Make sure your code is running as a JavaScript module (ESM), for example by using a <script type="module">
tag in your HTML document. Then Ky can be imported directly by that module without a bundler or other tools.
<script type="module">
import ky from 'https://unpkg.com/ky/distribution/index.js';
const json = await ky('https://jsonplaceholder.typicode.com/todos/1').json();
console.log(json.title);
//=> 'delectus aut autem'
</script>
How is it different from got
See my answer here. Got is maintained by the same people as Ky.
How is it different from axios
?
See my answer here.
How is it different from r2
?
See my answer in #10.
What does ky
mean?
It's just a random short npm package name I managed to get. It does, however, have a meaning in Japanese:
A form of text-able slang, KY is an abbreviation for 空æ°èªããªã (kuuki yomenai), which literally translates into âcannot read the air.â It's a phrase applied to someone who misses the implied meaning.
Browser support
The latest version of Chrome, Firefox, and Safari.
Node.js support
Node.js 18 and later.
Related
- fetch-extras - Useful utilities for working with Fetch
- got - Simplified HTTP requests for Node.js
- ky-hooks-change-case - Ky hooks to modify cases on requests and responses of objects
Maintainers
Top Related Projects
Promise based HTTP client for the browser and node.js
A light-weight module that brings the Fetch API to Node.js
The all-batteries-included GitHub SDK for Browsers, Node.js, and Deno.
Ajax for Node.js and browsers (JS HTTP client). Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.
🏊🏾 Simplified HTTP request client.
A window.fetch JavaScript polyfill.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot