Gathering detailed insights and metrics for ky
Gathering detailed insights and metrics for ky
Gathering detailed insights and metrics for ky
Gathering detailed insights and metrics for ky
🌳 Tiny & elegant JavaScript HTTP client based on the Fetch API
npm install ky
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
13,926 Stars
348 Commits
365 Forks
59 Watching
1 Branches
105 Contributors
Updated on 28 Nov 2024
Minified
Minified + Gzipped
TypeScript (100%)
Cumulative downloads
Total Downloads
Last day
-4.9%
373,050
Compared to previous day
Last week
4.3%
2,204,991
Compared to previous week
Last month
14.7%
9,015,263
Compared to previous month
Last year
22.3%
77,758,193
Compared to previous year
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.
fetch
ky.post()
).json()
supports generics and defaults to unknown
, not any
)1npm install ky
1import ky from 'ky'; 2 3const json = await ky.post('https://example.com', {json: {foo: true}}).json(); 4 5console.log(json); 6//=> `{data: '🦄'}`
With plain fetch
, it would be:
1class HTTPError extends Error {} 2 3const response = await fetch('https://example.com', { 4 method: 'POST', 5 body: JSON.stringify({foo: true}), 6 headers: { 7 'content-type': 'application/json' 8 } 9}); 10 11if (!response.ok) { 12 throw new HTTPError(`Fetch error: ${response.statusText}`); 13} 14 15const json = await response.json(); 16 17console.log(json); 18//=> `{data: '🦄'}`
If you are using Deno, import Ky from a URL. For example, using a CDN:
1import ky from 'https://esm.sh/ky';
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.
1import ky from 'ky'; 2 3const user = await ky('/api/user').json(); 4 5console.log(user);
⌨️ TypeScript: Accepts an optional type parameter, which defaults to unknown
, and is passed through to the return type of .json()
.
1import ky from 'ky'; 2 3// user1 is unknown 4const user1 = await ky('/api/users/1').json(); 5// user2 is a User 6const user2 = await ky<User>('/api/users/2').json(); 7// user3 is a User 8const user3 = await ky('/api/users/3').json<User>(); 9 10console.log([user1, user2, user3]);
Sets options.method
to the method name and makes a request.
⌨️ TypeScript: Accepts an optional type parameter for use with JSON responses (see ky()
).
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.
Type: object
Same as fetch
options, plus the following additional options:
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.
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.
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()
.
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.
1import ky from 'ky'; 2 3// On https://example.com 4 5const response = await ky('unicorn', {prefixUrl: '/api'}); 6//=> 'https://example.com/api/unicorn' 7 8const response2 = await ky('unicorn', {prefixUrl: 'https://cats.com'}); 9//=> 'https://cats.com/unicorn'
Notes:
prefixUrl
and input
are joined, the result is resolved against the base URL of the page (if any).input
are disallowed when using this option to enforce consistency and avoid confusion about how the input
URL is handled, given that input
will not follow the normal URL resolution rules when prefixUrl
is being used, which changes the meaning of a leading slash.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.
1import ky from 'ky'; 2 3const json = await ky('https://example.com', { 4 retry: { 5 limit: 10, 6 methods: ['get'], 7 statusCodes: [413], 8 backoffLimit: 3000 9 } 10}).json();
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.
Type: object<string, Function[]>
Default: {beforeRequest: [], beforeRetry: [], afterResponse: []}
Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially.
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.
1import ky from 'ky'; 2 3const api = ky.extend({ 4 hooks: { 5 beforeRequest: [ 6 request => { 7 request.headers.set('X-Requested-With', 'ky'); 8 } 9 ] 10 } 11}); 12 13const response = await api.get('https://example.com/api/users');
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).
1import ky from 'ky'; 2 3const response = await ky('https://example.com', { 4 hooks: { 5 beforeRetry: [ 6 async ({request, options, error, retryCount}) => { 7 const token = await ky('https://example.com/refresh-token'); 8 request.headers.set('Authorization', `token ${token}`); 9 } 10 ] 11 } 12});
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
.
1import ky from 'ky'; 2 3await ky('https://example.com', { 4 hooks: { 5 beforeError: [ 6 error => { 7 const {response} = error; 8 if (response && response.body) { 9 error.name = 'GitHubError'; 10 error.message = `${response.body.message} (${response.status})`; 11 } 12 13 return error; 14 } 15 ] 16 } 17});
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
.
1import ky from 'ky'; 2 3const response = await ky('https://example.com', { 4 hooks: { 5 afterResponse: [ 6 (_request, _options, response) => { 7 // You could do something with the response, for example, logging. 8 log(response); 9 10 // Or return a `Response` instance to overwrite the response. 11 return new Response('A different response', {status: 200}); 12 }, 13 14 // Or retry with a fresh token on a 403 error 15 async (request, options, response) => { 16 if (response.status === 403) { 17 // Get a fresh token 18 const token = await ky('https://example.com/token').text(); 19 20 // Retry with the token 21 request.headers.set('Authorization', `token ${token}`); 22 23 return ky(request); 24 } 25 } 26 ] 27 } 28});
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.
Type: Function
Download progress event handler.
The function receives a progress
and chunk
argument:
progress
object contains the following elements: percent
, transferredBytes
and totalBytes
. If it's not possible to retrieve the body size, totalBytes
will be 0
.chunk
argument is an instance of Uint8Array
. It's empty for the first call.1import ky from 'ky'; 2 3const response = await ky('https://example.com', { 4 onDownloadProgress: (progress, chunk) => { 5 // Example output: 6 // `0% - 0 of 1271 bytes` 7 // `100% - 1271 of 1271 bytes` 8 console.log(`${progress.percent * 100}% - ${progress.transferredBytes} of ${progress.totalBytes} bytes`); 9 } 10});
Type: Function
Default: JSON.parse()
User-defined JSON-parsing function.
Use-cases:
bourne
package to protect from prototype pollution.reviver
option of JSON.parse()
.1import ky from 'ky'; 2import bourne from '@hapijs/bourne'; 3 4const json = await ky('https://example.com', { 5 parseJson: text => bourne(text) 6}).json();
Type: Function
Default: JSON.stringify()
User-defined JSON-stringifying function.
Use-cases:
replacer
function.1import ky from 'ky'; 2import {DateTime} from 'luxon'; 3 4const json = await ky('https://example.com', { 5 stringifyJson: data => JSON.stringify(data, (key, value) => { 6 if (key.endsWith('_at')) { 7 return DateTime.fromISO(value).toSeconds(); 8 } 9 10 return value; 11 }) 12}).json();
Type: Function
Default: fetch
User-defined fetch
function.
Has to be fully compatible with the Fetch API standard.
Use-cases:
fetch
implementations like isomorphic-unfetch
.fetch
wrapper function provided by some frameworks that use server-side rendering (SSR).1import ky from 'ky'; 2import fetch from 'isomorphic-unfetch'; 3 4const json = await ky('https://example.com', {fetch}).json();
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
.
1import ky from 'ky'; 2 3const url = 'https://sindresorhus.com'; 4 5const original = ky.create({ 6 headers: { 7 rainbow: 'rainbow', 8 unicorn: 'unicorn' 9 }, 10 hooks: { 11 beforeRequest: [ () => console.log('before 1') ], 12 afterResponse: [ () => console.log('after 1') ], 13 }, 14}); 15 16const extended = original.extend({ 17 headers: { 18 rainbow: undefined 19 }, 20 hooks: { 21 beforeRequest: undefined, 22 afterResponse: [ () => console.log('after 2') ], 23 } 24}); 25 26const response = await extended(url).json(); 27//=> after 1 28//=> after 2 29 30console.log('rainbow' in response); 31//=> false 32 33console.log('unicorn' in response); 34//=> true
You can also refer to parent defaults by providing a function to .extend()
.
1import ky from 'ky'; 2 3const api = ky.create({prefixUrl: 'https://example.com/api'}); 4 5const usersApi = api.extend((options) => ({prefixUrl: `${options.prefixUrl}/users`})); 6 7const response = await usersApi.get('123'); 8//=> 'https://example.com/api/users/123' 9 10const response = await api.get('version'); 11//=> 'https://example.com/api/version'
Create a new Ky instance with complete new defaults.
1import ky from 'ky'; 2 3// On https://my-site.com 4 5const api = ky.create({prefixUrl: 'https://example.com/api'}); 6 7const response = await api.get('users/123'); 8//=> 'https://example.com/api/users/123' 9 10const response = await api.get('/status', {prefixUrl: ''}); 11//=> 'https://my-site.com/status'
Type: object
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.
1import ky from 'ky'; 2 3const options = { 4 hooks: { 5 beforeRetry: [ 6 async ({request, options, error, retryCount}) => { 7 const shouldStopRetry = await ky('https://example.com/api'); 8 if (shouldStopRetry) { 9 return ky.stop; 10 } 11 } 12 ] 13 } 14}; 15 16// Note that response will be `undefined` in case `ky.stop` is returned. 17const response = await ky.post('https://example.com', options); 18 19// Using `.text()` or other body methods is not supported. 20const text = await ky('https://example.com', options).text();
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:
1try { 2 await ky('https://example.com').json(); 3} catch (error) { 4 if (error.name === 'HTTPError') { 5 const errorJson = await error.response.json(); 6 } 7}
⌨️ TypeScript: Accepts an optional type parameter, which defaults to unknown
, and is passed through to the return type of error.response.json()
.
The error thrown when the request times out. It has a request
property with the Request
object.
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
.
1import ky from 'ky'; 2 3// `multipart/form-data` 4const formData = new FormData(); 5formData.append('food', 'fries'); 6formData.append('drink', 'icetea'); 7 8const 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
.
1import ky from 'ky'; 2 3// `application/x-www-form-urlencoded` 4const searchParams = new URLSearchParams(); 5searchParams.set('food', 'fries'); 6searchParams.set('drink', 'icetea'); 7 8const response = await ky.post(url, {body: searchParams});
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.
1import ky from 'ky'; 2 3const json = await ky.post('https://example.com', { 4 headers: { 5 'content-type': 'application/json' 6 }, 7 json: { 8 foo: true 9 }, 10}).json(); 11 12console.log(json); 13//=> `{data: '🦄'}`
Fetch (and hence Ky) has built-in support for request cancellation through the AbortController
API. Read more.
Example:
1import ky from 'ky'; 2 3const controller = new AbortController(); 4const {signal} = controller; 5 6setTimeout(() => { 7 controller.abort(); 8}, 5000); 9 10try { 11 console.log(await ky(url, {signal}).text()); 12} catch (error) { 13 if (error.name === 'AbortError') { 14 console.log('Fetch aborted'); 15 } else { 16 console.error('Fetch error:', error); 17 } 18}
Node.js 18 and later supports fetch
natively, so you can just use this package directly.
Same as above.
Either use a test runner that can run in the browser, like Mocha, or use AVA with ky-universal
. Read more.
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.
1<script type="module"> 2import ky from 'https://unpkg.com/ky/distribution/index.js'; 3 4const json = await ky('https://jsonplaceholder.typicode.com/todos/1').json(); 5 6console.log(json.title); 7//=> 'delectus aut autem' 8</script>
got
See my answer here. Got is maintained by the same people as Ky.
axios
?See my answer here.
r2
?See my answer in #10.
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.
The latest version of Chrome, Firefox, and Safari.
Node.js 18 and later.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
security policy file detected
Details
Reason
3 commit(s) and 16 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
Found 15/30 approved changesets -- score normalized to 5
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More