Skip to content

🌳 Tiny & elegant JavaScript HTTP client based on the Fetch API

License

Notifications You must be signed in to change notification settings

sindresorhus/ky

Repository files navigation

Ky is a tiny and elegant HTTP client based on theFetch API

Coverage Status

Ky targetsmodern browsers,Node.js, Bun, and Deno.

It's just a tiny package with no dependencies.

Benefits over plainfetch

  • 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()resolves tounknown,notany;.json<T>()can be used too)

Install

npm install ky
Download
CDN

Usage

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';

API

ky(input, options?)

Theinputandoptionsare the same asfetch,with some exceptions:

  • Thecredentialsoption issame-originby default, which is the default in the spec too, but not all browsers have caught up yet.
  • Adds some more options. See below.

Returns aResponseobjectwithBodymethodsadded for convenience. So you can, for example, callky.get(input).json()directly without having to await theResponsefirst. When called like that, an appropriateAcceptheader will be set depending on the body method used. Unlike theBodymethods ofwindow.Fetch;these will throw anHTTPErrorif 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 is204instead of throwing a parse error due to an empty body.

ky.get(input, options?)

ky.post(input, options?)

ky.put(input, options?)

ky.patch(input, options?)

ky.head(input, options?)

ky.delete(input, options?)

Setsoptions.methodto the method name and makes a request.

When using aRequestinstance asinput,any URL altering options (such asprefixUrl) will be ignored.

options

Type:object

In addition to all thefetchoptions,it supports these options:

method

Type:string
Default:'get'

HTTP method used to make the request.

Internally, the standard methods (GET,POST,PUT,PATCH,HEADandDELETE) are uppercased in order to avoid server errors due to case sensitivity.

json

Type:objectand any other value accepted byJSON.stringify()

Shortcut for sending JSON. Use this instead of thebodyoption. Accepts any plain object or value, which will beJSON.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 byURLSearchParams().

prefixUrl

Type:string | URL

A prefix to prepend to theinputURL 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 wheninputis a string. Theinputargument 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:

  • AfterprefixUrlandinputare joined, the result is resolved against thebase URLof the page (if any).
  • Leading slashes ininputare disallowed when using this option to enforce consistency and avoid confusion about how theinputURL is handled, given thatinputwill not follow the normal URL resolution rules whenprefixUrlis being used, which changes the meaning of a leading slash.
retry

Type:object | number
Default:

  • limit:2
  • methods:getputheaddeleteoptionstrace
  • statusCodes:408413429500502503504
  • afterStatusCodes:413,429,503
  • maxRetryAfter:undefined
  • backoffLimit:undefined
  • delay:attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000

An object representinglimit,methods,statusCodes,afterStatusCodes,andmaxRetryAfterfields for maximum retry count, allowed methods, allowed status codes, status codes allowed to use theRetry-Aftertime, and maximumRetry-Aftertime.

Ifretryis a number, it will be used aslimitand other defaults will remain in place.

If the response provides an HTTP status contained inafterStatusCodes,Ky will wait until the date or timeout given in theRetry-Afterheader has passed to retry the request. If the provided status code is not in the list, theRetry-Afterheader will be ignored.

IfmaxRetryAfteris set toundefined,it will useoptions.timeout.IfRetry-Afterheader is greater thanmaxRetryAfter,it will usemaxRetryAfter.

ThebackoffLimitoption is the upper limit of the delay per retry in milliseconds. To clamp the delay, setbackoffLimitto 1000, for example. By default, the delay is calculated with0.3 * (2 ** (attemptCount - 1)) * 1000.The delay increases exponentially.

Thedelayoption 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();
timeout

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.

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 receivesrequestandoptionsas arguments. You could, for example, modify therequest.headershere.

The hook can return aRequestto replace the outgoing request, or return aResponseto 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 remainingbeforeRequesthooks 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');
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, modifyrequest.headershere.

If the request received a response, the error will be of typeHTTPErrorand theResponseobject 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 thebeforeRetryhooks will not be called in this case. Alternatively, you can return theky.stopsymbol to do the same thing but without propagating an error (this has some limitations, seeky.stopdocs 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}`);
}
]
}
});
hooks.beforeError

Type:Function[]
Default:[]

This hook enables you to modify theHTTPErrorright before it is thrown. The hook function receives aHTTPErroras 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;
}
]
}
});
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 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);
}
}
]
}
});
throwHttpErrors

Type:boolean
Default:true

Throw anHTTPErrorwhen, after following redirects, the response has a non-2xx status code. To also throw for redirects instead of following them, set theredirectoption to'manual'.

Setting this tofalsemay 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.

onDownloadProgress

Type:Function

Download progress event handler.

The function receives aprogressandchunkargument:

  • Theprogressobject contains the following elements:percent,transferredBytesandtotalBytes.If it's not possible to retrieve the body size,totalByteswill be0.
  • Thechunkargument 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`);
}
});
parseJson

Type:Function
Default:JSON.parse()

User-defined JSON-parsing function.

Use-cases:

  1. Parse JSON via thebournepackageto protect from prototype pollution.
  2. Parse JSON withreviveroption ofJSON.parse().
importkyfrom'ky';
importbournefrom'@hapijs/bourne';

constjson=awaitky('https://example ',{
parseJson:text=>bourne(text)
}).json();
stringifyJson

Type:Function
Default:JSON.stringify()

User-defined JSON-stringifying function.

Use-cases:

  1. Stringify JSON with a customreplacerfunction.
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();
fetch

Type:Function
Default:fetch

User-definedfetchfunction. Has to be fully compatible with theFetch APIstandard.

Use-cases:

  1. Use customfetchimplementations likeisomorphic-unfetch.
  2. Use thefetchwrapper function provided by some frameworks that use server-side rendering (SSR).
importkyfrom'ky';
importfetchfrom'isomorphic-unfetch';

constjson=awaitky('https://example ',{fetch}).json();

ky.extend(defaultOptions)

Create a newkyinstance with some defaults overridden with your own.

In contrast toky.create(),ky.extend()inherits defaults from its parent.

You can pass headers as aHeadersinstance or a plain object.

You can remove a header with.extend()by passing the header with anundefinedvalue. Passingundefinedas a string removes the header only if it comes from aHeadersinstance.

Similarly, you can remove existinghooksentries 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'

ky.create(defaultOptions)

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'

defaultOptions

Type:object

ky.stop

ASymbolthat can be returned by abeforeRetryhook to stop the retry. This will also short circuit the remainingbeforeRetryhooks.

Note: Returning this symbol makes Ky abort and return with anundefinedresponse. 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.stopis 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();

HTTPError

Exposed forinstanceofchecks. The error has aresponseproperty with theResponseobject,requestproperty with theRequestobject,andoptionsproperty with normalized options (either passed tokywhen creating an instance withky.create()or directly when performing the request).

If you need to read the actual response when anHTTPErrorhas 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();
}
}

TimeoutError

The error thrown when the request times out. It has arequestproperty with theRequestobject.

Tips

Sending form data

Sending form data in Ky is identical tofetch.Just pass aFormDatainstance to thebodyoption. TheContent-Typeheader 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-urlencodedformat, 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});

Setting a customContent-Type

Ky automatically sets an appropriateContent-Typeheader 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 theheadersoption, 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: '🦄'}`

Cancellation

Fetch (and hence Ky) has built-in support for request cancellation through theAbortControllerAPI.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);
}
}

FAQ

How do I use this in Node.js?

Node.js 18 and later supportsfetchnatively, 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 useAVAwithky-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.

<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.

What doeskymean?

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.

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