Sindre's open source work is supported by the community.
Special thanks to:
Ky is a tiny and elegant HTTP client based on theFetch API
Ky targetsmodern browsers,Node.js, Bun, and Deno.
It's just a tiny package with no dependencies.
- 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
)
npm install ky
importkyfrom'ky';
constjson=awaitky.post('https://example ',{json:{foo:true}}).json();
console.log(json);
//=> `{data: '🦄'}`
With plainfetch
,it would be:
classHTTPErrorextendsError{}
constresponse=awaitfetch('https://example ',{
method:'POST',
body:JSON.stringify({foo:true}),
headers:{
'content-type':'application/json'
}
});
if(!response.ok){
thrownewHTTPError(`Fetch error:${response.statusText}`);
}
constjson=awaitresponse.json();
console.log(json);
//=> `{data: '🦄'}`
If you are usingDeno,import Ky from a URL. For example, using a CDN:
importkyfrom'https://esm.sh/ky';
Theinput
andoptions
are the same asfetch
,with additionaloptions
available (see below).
Returns aResponse
objectwithBody
methodsadded for convenience. So you can, for example, callky.get(input).json()
directly without having to await theResponse
first. When called like that, an appropriateAccept
header will be set depending on the body method used. Unlike theBody
methods ofwindow.Fetch
;these will throw anHTTPError
if the response status is not in the range of200...299
.Also,.json()
will return an empty string if body is empty or the response status is204
instead of throwing a parse error due to an empty body.
importkyfrom'ky';
constuser=awaitky('/api/user').json();
console.log(user);
⌨️TypeScript:Accepts an optionaltype parameter,which defaults tounknown
,and is passed through to the return type of.json()
.
importkyfrom'ky';
// user1 is unknown
constuser1=awaitky('/api/users/1').json();
// user2 is a User
constuser2=awaitky<User>('/api/users/2').json();
// user3 is a User
constuser3=awaitky('/api/users/3').json<User>();
console.log([user1,user2,user3]);
Setsoptions.method
to the method name and makes a request.
⌨️TypeScript:Accepts an optional type parameter for use with JSON responses (seeky()
).
Type:string
|URL
|Request
Same asfetch
input.
When using aRequest
instance asinput
,any URL altering options (such asprefixUrl
) will be ignored.
Type:object
Same asfetch
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
andDELETE
) are uppercased in order to avoid server errors due to case sensitivity.
Type:object
and any other value accepted byJSON.stringify()
Shortcut for sending JSON. Use this instead of thebody
option. Accepts any plain object or value, which will beJSON.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 byURLSearchParams()
.
Type:string | URL
A prefix to prepend to theinput
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 withinput
.Only takes effect wheninput
is a string. Theinput
argument cannot start with a slash/
when using this option.
Useful when used withky.extend()
to create niche-specific Ky-instances.
importkyfrom'ky';
// On https://example
constresponse=awaitky('unicorn',{prefixUrl:'/api'});
//=> 'https://example /api/unicorn'
constresponse2=awaitky('unicorn',{prefixUrl:'https://cats '});
//=> 'https://cats /unicorn'
Notes:
- After
prefixUrl
andinput
are joined, the result is resolved against thebase URLof 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.
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 representinglimit
,methods
,statusCodes
,afterStatusCodes
,andmaxRetryAfter
fields for maximum retry count, allowed methods, allowed status codes, status codes allowed to use theRetry-After
time, and maximumRetry-After
time.
Ifretry
is a number, it will be used aslimit
and other defaults will remain in place.
If the response provides an HTTP status contained inafterStatusCodes
,Ky will wait until the date, timeout, or timestamp given in theRetry-After
header has passed to retry the request. IfRetry-After
is missing, the non-standardRateLimit-Reset
header is used in its place as a fallback. If the provided status code is not in the list, theRetry-After
header will be ignored.
IfmaxRetryAfter
is set toundefined
,it will useoptions.timeout
.IfRetry-After
header is greater thanmaxRetryAfter
,it will usemaxRetryAfter
.
ThebackoffLimit
option is the upper limit of the delay per retry in milliseconds.
To clamp the delay, setbackoffLimit
to 1000, for example.
By default, the delay is calculated with0.3 * (2 ** (attemptCount - 1)) * 1000
.The delay increases exponentially.
Thedelay
option can be used to change how the delay between retries is calculated. The function receives one parameter, the attempt count, starting at1
.
Retries are not triggered following atimeout.
importkyfrom'ky';
constjson=awaitky('https://example ',{
retry:{
limit:10,
methods:['get'],
statusCodes:[413],
backoffLimit:3000
}
}).json();
Type:number | false
Default:10000
Timeout in milliseconds for getting a response, including any retries. Can not be greater than 2147483647.
If set tofalse
,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 receivesrequest
andoptions
as arguments. You could, for example, modify therequest.headers
here.
The hook can return aRequest
to replace the outgoing request, or return aResponse
to completely avoid making an HTTP request. This can be used to mock a request, check an internal cache, etc. Animportantconsideration when returning a request or response from this hook is that any remainingbeforeRequest
hooks will be skipped, so you may want to only return them from the last hook.
importkyfrom'ky';
constapi=ky.extend({
hooks:{
beforeRequest:[
request=>{
request.headers.set('X-Requested-With','ky');
}
]
}
});
constresponse=awaitapi.get('https://example /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, modifyrequest.headers
here.
If the request received a response, the error will be of typeHTTPError
and theResponse
object will be available aterror.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 ofHTTPError
.
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 thebeforeRetry
hooks will not be called in this case. Alternatively, you can return theky.stop
symbol to do the same thing but without propagating an error (this has some limitations, seeky.stop
docs for details).
importkyfrom'ky';
constresponse=awaitky('https://example ',{
hooks:{
beforeRetry:[
async({request,options,error,retryCount})=>{
consttoken=awaitky('https://example /refresh-token');
request.headers.set('Authorization',`token${token}`);
}
]
}
});
Type:Function[]
Default:[]
This hook enables you to modify theHTTPError
right before it is thrown. The hook function receives aHTTPError
as an argument and should return an instance ofHTTPError
.
importkyfrom'ky';
awaitky('https://example ',{
hooks:{
beforeError:[
error=>{
const{response}=error;
if(response&&response.body){
error.name='GitHubError';
error.message=`${response.body.message}(${response.status})`;
}
returnerror;
}
]
}
});
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 ofResponse
.
importkyfrom'ky';
constresponse=awaitky('https://example ',{
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.
returnnewResponse('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
consttoken=awaitky('https://example /token').text();
// Retry with the token
request.headers.set('Authorization',`token${token}`);
returnky(request);
}
}
]
}
});
Type:boolean
Default:true
Throw anHTTPError
when, after following redirects, the response has a non-2xx status code. To also throw for redirects instead of following them, set theredirect
option to'manual'
.
Setting this tofalse
may be useful if you are checking for resource availability and are expecting error responses.
Note: Iffalse
,error responses are considered successful and the request will not be retried.
Type:Function
Download progress event handler.
The function receives aprogress
andchunk
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.
importkyfrom'ky';
constresponse=awaitky('https://example ',{
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`);
}
});
Type:Function
Default:JSON.parse()
User-defined JSON-parsing function.
Use-cases:
- Parse JSON via the
bourne
packageto protect from prototype pollution. - Parse JSON with
reviver
option ofJSON.parse()
.
importkyfrom'ky';
importbournefrom'@hapijs/bourne';
constjson=awaitky('https://example ',{
parseJson:text=>bourne(text)
}).json();
Type:Function
Default:JSON.stringify()
User-defined JSON-stringifying function.
Use-cases:
- Stringify JSON with a custom
replacer
function.
importkyfrom'ky';
import{DateTime}from'luxon';
constjson=awaitky('https://example ',{
stringifyJson:data=>JSON.stringify(data,(key,value)=>{
if(key.endsWith('_at')){
returnDateTime.fromISO(value).toSeconds();
}
returnvalue;
})
}).json();
Type:Function
Default:fetch
User-definedfetch
function.
Has to be fully compatible with theFetch APIstandard.
Use-cases:
- Use custom
fetch
implementations likeisomorphic-unfetch
. - Use the
fetch
wrapper function provided by some frameworks that use server-side rendering (SSR).
importkyfrom'ky';
importfetchfrom'isomorphic-unfetch';
constjson=awaitky('https://example ',{fetch}).json();
Create a newky
instance with some defaults overridden with your own.
In contrast toky.create()
,ky.extend()
inherits defaults from its parent.
You can pass headers as aHeaders
instance or a plain object.
You can remove a header with.extend()
by passing the header with anundefined
value.
Passingundefined
as a string removes the header only if it comes from aHeaders
instance.
Similarly, you can remove existinghooks
entries by extending the hook with an explicitundefined
.
importkyfrom'ky';
consturl='https://sindresorhus ';
constoriginal=ky.create({
headers:{
rainbow:'rainbow',
unicorn:'unicorn'
},
hooks:{
beforeRequest:[()=>console.log('before 1')],
afterResponse:[()=>console.log('after 1')],
},
});
constextended=original.extend({
headers:{
rainbow:undefined
},
hooks:{
beforeRequest:undefined,
afterResponse:[()=>console.log('after 2')],
}
});
constresponse=awaitextended(url).json();
//=> after 1
//=> after 2
console.log('rainbow'inresponse);
//=> false
console.log('unicorn'inresponse);
//=> true
You can also refer to parent defaults by providing a function to.extend()
.
importkyfrom'ky';
constapi=ky.create({prefixUrl:'https://example /api'});
constusersApi=api.extend((options)=>({prefixUrl:`${options.prefixUrl}/users`}));
constresponse=awaitusersApi.get('123');
//=> 'https://example /api/users/123'
constresponse=awaitapi.get('version');
//=> 'https://example /api/version'
Create a new Ky instance with complete new defaults.
importkyfrom'ky';
// On https://my-site
constapi=ky.create({prefixUrl:'https://example /api'});
constresponse=awaitapi.get('users/123');
//=> 'https://example /api/users/123'
constresponse=awaitapi.get('/status',{prefixUrl:''});
//=> 'https://my-site /status'
Type:object
ASymbol
that can be returned by abeforeRetry
hook to stop the retry. This will also short circuit the remainingbeforeRetry
hooks.
Note: Returning this symbol makes Ky abort and return with anundefined
response. Be sure to check for a response before accessing any properties on it or useoptional 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 forky.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.
importkyfrom'ky';
constoptions={
hooks:{
beforeRetry:[
async({request,options,error,retryCount})=>{
constshouldStopRetry=awaitky('https://example /api');
if(shouldStopRetry){
returnky.stop;
}
}
]
}
};
// Note that response will be `undefined` in case `ky.stop` is returned.
constresponse=awaitky.post('https://example ',options);
// Using `.text()` or other body methods is not supported.
consttext=awaitky('https://example ',options).text();
Exposed forinstanceof
checks. The error has aresponse
property with theResponse
object,request
property with theRequest
object,andoptions
property with normalized options (either passed toky
when creating an instance withky.create()
or directly when performing the request).
If you need to read the actual response when anHTTPError
has occurred, call the respective parser method on the response object. For example:
try{
awaitky('https://example ').json();
}catch(error){
if(error.name==='HTTPError'){
consterrorJson=awaiterror.response.json();
}
}
⌨️TypeScript:Accepts an optionaltype parameter,which defaults tounknown
,and is passed through to the return type oferror.response.json()
.
The error thrown when the request times out. It has arequest
property with theRequest
object.
Sending form data in Ky is identical tofetch
.Just pass aFormData
instance to thebody
option. TheContent-Type
header will be automatically set tomultipart/form-data
.
importkyfrom'ky';
// `multipart/form-data`
constformData=newFormData();
formData.append('food','fries');
formData.append('drink','icetea');
constresponse=awaitky.post(url,{body:formData});
If you want to send the data inapplication/x-www-form-urlencoded
format, you will need to encode the data withURLSearchParams
.
importkyfrom'ky';
// `application/x-www-form-urlencoded`
constsearchParams=newURLSearchParams();
searchParams.set('food','fries');
searchParams.set('drink','icetea');
constresponse=awaitky.post(url,{body:searchParams});
Ky automatically sets an appropriateContent-Type
header for each request based on the data in the request body. However, some APIs require custom, non-standard content types, such asapplication/x-amz-json-1.1
.Using theheaders
option, you can manually override the content type.
importkyfrom'ky';
constjson=awaitky.post('https://example ',{
headers:{
'content-type':'application/json'
},
json:{
foo:true
},
}).json();
console.log(json);
//=> `{data: '🦄'}`
Fetch (and hence Ky) has built-in support for request cancellation through theAbortController
API.Read more.
Example:
importkyfrom'ky';
constcontroller=newAbortController();
const{signal}=controller;
setTimeout(()=>{
controller.abort();
},5000);
try{
console.log(awaitky(url,{signal}).text());
}catch(error){
if(error.name==='AbortError'){
console.log('Fetch aborted');
}else{
console.error('Fetch error:',error);
}
}
Node.js 18 and later supportsfetch
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 useAVAwithky-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.
<scripttype= "module">
importkyfrom'https://unpkg /ky/distribution/index.js';
constjson=awaitky('https://jsonplaceholder.typicode /todos/1').json();
console.log(json.title);
//=> 'delectus aut autem'
</script>
How is it different fromgot
See my answerhere.Got is maintained by the same people as Ky.
How is it different fromaxios
?
See my answerhere.
How is it different fromr2
?
See my answer in#10.
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 không khí đọc めない (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.
- 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