UNPKG

22.8 kBMarkdownView Raw
1<div align="center">
2 <br>
3 <div>
4 <img width="600" height="600" src="media/logo.svg" alt="ky">
5 </div>
6 <p align="center">Huge thanks to <a href="https://lunanode.com"><img src="https://sindresorhus.com/assets/thanks/lunanode-logo.svg" width="170"></a> for sponsoring me!</p>
7 <br>
8 <br>
9 <br>
10 <br>
11</div>
12
13> Ky is a tiny and elegant HTTP client based on the browser [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch)
14
15[![Coverage Status](https://codecov.io/gh/sindresorhus/ky/branch/main/graph/badge.svg)](https://codecov.io/gh/sindresorhus/ky)
16[![](https://badgen.net/bundlephobia/minzip/ky)](https://bundlephobia.com/result?p=ky)
17
18Ky targets [modern browsers](#browser-support) and [Deno](https://github.com/denoland/deno). For older browsers, you will need to transpile and use a [`fetch` polyfill](https://github.com/github/fetch) and [`globalThis` polyfill](https://github.com/es-shims/globalThis). For Node.js, check out [Got](https://github.com/sindresorhus/got). For isomorphic needs (like SSR), check out [`ky-universal`](https://github.com/sindresorhus/ky-universal).
19
20It's just a tiny file with no dependencies.
21
22## Benefits over plain `fetch`
23
24- Simpler API
25- Method shortcuts (`ky.post()`)
26- Treats non-2xx status codes as errors (after redirects)
27- Retries failed requests
28- JSON option
29- Timeout support
30- URL prefix option
31- Instances with custom defaults
32- Hooks
33
34## Install
35
36```
37$ npm install ky
38```
39
40###### Download
41
42- [Normal](https://cdn.jsdelivr.net/npm/ky/index.js)
43- [Minified](https://cdn.jsdelivr.net/npm/ky/index.min.js)
44
45###### CDN
46
47- [jsdelivr](https://www.jsdelivr.com/package/npm/ky)
48- [unpkg](https://unpkg.com/ky)
49
50## Usage
51
52```js
53import ky from 'ky';
54
55const json = await ky.post('https://example.com', {json: {foo: true}}).json();
56
57console.log(json);
58//=> `{data: '🦄'}`
59```
60
61With plain `fetch`, it would be:
62
63```js
64class HTTPError extends Error {}
65
66const response = await fetch('https://example.com', {
67 method: 'POST',
68 body: JSON.stringify({foo: true}),
69 headers: {
70 'content-type': 'application/json'
71 }
72});
73
74if (!response.ok) {
75 throw new HTTPError(`Fetch error: ${response.statusText}`);
76}
77
78const json = await response.json();
79
80console.log(json);
81//=> `{data: '🦄'}`
82```
83
84If you are using [Deno](https://github.com/denoland/deno), import Ky from a URL. For example, using a CDN:
85
86```js
87import ky from 'https://cdn.skypack.dev/ky?dts';
88```
89
90## API
91
92### ky(input, options?)
93
94The `input` and `options` are the same as [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch), with some exceptions:
95
96- The `credentials` option is `same-origin` by default, which is the default in the spec too, but not all browsers have caught up yet.
97- Adds some more options. See below.
98
99Returns a [`Response` object](https://developer.mozilla.org/en-US/docs/Web/API/Response) with [`Body` methods](https://developer.mozilla.org/en-US/docs/Web/API/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 the response status is `204` instead of throwing a parse error due to an empty body.
100
101### ky.get(input, options?)
102### ky.post(input, options?)
103### ky.put(input, options?)
104### ky.patch(input, options?)
105### ky.head(input, options?)
106### ky.delete(input, options?)
107
108Sets `options.method` to the method name and makes a request.
109
110When using a `Request` instance as `input`, any URL altering options (such as `prefixUrl`) will be ignored.
111
112#### options
113
114Type: `object`
115
116##### method
117
118Type: `string`\
119Default: `'get'`
120
121HTTP method used to make the request.
122
123Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD` and `DELETE`) are uppercased in order to avoid server errors due to case sensitivity.
124
125##### json
126
127Type: `object` and any other value accepted by [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)
128
129Shortcut 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.
130
131##### searchParams
132
133Type: `string | object<string, string | number | boolean> | Array<Array<string | number | boolean>> | URLSearchParams`\
134Default: `''`
135
136Search parameters to include in the request URL. Setting this will override all existing search parameters in the input URL.
137
138Accepts any value supported by [`URLSearchParams()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams).
139
140##### prefixUrl
141
142Type: `string | URL`
143
144A 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.
145
146Useful when used with [`ky.extend()`](#kyextenddefaultoptions) to create niche-specific Ky-instances.
147
148```js
149import ky from 'ky';
150
151// On https://example.com
152
153const response = await ky('unicorn', {prefixUrl: '/api'});
154//=> 'https://example.com/api/unicorn'
155
156const response2 = await ky('unicorn', {prefixUrl: 'https://cats.com'});
157//=> 'https://cats.com/unicorn'
158```
159
160Notes:
161 - After `prefixUrl` and `input` are joined, the result is resolved against the [base URL](https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI) of the page (if any).
162 - Leading slashes in `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.
163
164##### retry
165
166Type: `object | number`\
167Default:
168- `limit`: `2`
169- `methods`: `get` `put` `head` `delete` `options` `trace`
170- `statusCodes`: [`408`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) [`413`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/413) [`429`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) [`500`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500) [`502`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/502) [`503`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503) [`504`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504)
171- `maxRetryAfter`: `undefined`
172
173An object representing `limit`, `methods`, `statusCodes` and `maxRetryAfter` fields for maximum retry count, allowed methods, allowed status codes and maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time.
174
175If `retry` is a number, it will be used as `limit` and other defaults will remain in place.
176
177If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`. If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.
178
179Delays between retries is calculated with the function `0.3 * (2 ** (retry - 1)) * 1000`, where `retry` is the attempt number (starts from 1).
180
181Retries are not triggered following a [timeout](#timeout).
182
183```js
184import ky from 'ky';
185
186const json = await ky('https://example.com', {
187 retry: {
188 limit: 10,
189 methods: ['get'],
190 statusCodes: [413]
191 }
192}).json();
193```
194
195##### timeout
196
197Type: `number | false`\
198Default: `10000`
199
200Timeout in milliseconds for getting a response, including any retries. Can not be greater than 2147483647.
201If set to `false`, there will be no timeout.
202
203##### hooks
204
205Type: `object<string, Function[]>`\
206Default: `{beforeRequest: [], beforeRetry: [], afterResponse: []}`
207
208Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially.
209
210###### hooks.beforeRequest
211
212Type: `Function[]`\
213Default: `[]`
214
215This 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.
216
217The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing request, or return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/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.
218
219```js
220import ky from 'ky';
221
222const api = ky.extend({
223 hooks: {
224 beforeRequest: [
225 request => {
226 request.headers.set('X-Requested-With', 'ky');
227 }
228 ]
229 }
230});
231
232const response = await api.get('https://example.com/api/users');
233```
234
235###### hooks.beforeRetry
236
237Type: `Function[]`\
238Default: `[]`
239
240This 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.
241
242If 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`.
243
244You 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`](#kystop) symbol to do the same thing but without propagating an error (this has some limitations, see `ky.stop` docs for details).
245
246```js
247import ky from 'ky';
248
249const response = await ky('https://example.com', {
250 hooks: {
251 beforeRetry: [
252 async ({request, options, error, retryCount}) => {
253 const token = await ky('https://example.com/refresh-token');
254 request.headers.set('Authorization', `token ${token}`);
255 }
256 ]
257 }
258});
259```
260
261###### hooks.beforeError
262
263Type: `Function[]`\
264Default: `[]`
265
266This 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`.
267
268```js
269import ky from 'ky';
270
271await ky('https://example.com', {
272 hooks: {
273 beforeError: [
274 error => {
275 const {response} = error;
276 if (response && response.body) {
277 error.name = 'GitHubError';
278 error.message = `${response.body.message} (${response.statusCode})`;
279 }
280
281 return error;
282 }
283 ]
284 }
285});
286```
287
288###### hooks.afterResponse
289
290Type: `Function[]`\
291Default: `[]`
292
293This 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`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
294
295```js
296import ky from 'ky';
297
298const response = await ky('https://example.com', {
299 hooks: {
300 afterResponse: [
301 (_request, _options, response) => {
302 // You could do something with the response, for example, logging.
303 log(response);
304
305 // Or return a `Response` instance to overwrite the response.
306 return new Response('A different response', {status: 200});
307 },
308
309 // Or retry with a fresh token on a 403 error
310 async (request, options, response) => {
311 if (response.status === 403) {
312 // Get a fresh token
313 const token = await ky('https://example.com/token').text();
314
315 // Retry with the token
316 request.headers.set('Authorization', `token ${token}`);
317
318 return ky(request);
319 }
320 }
321 ]
322 }
323});
324```
325
326##### throwHttpErrors
327
328Type: `boolean`\
329Default: `true`
330
331Throw 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`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) option to `'manual'`.
332
333Setting this to `false` may be useful if you are checking for resource availability and are expecting error responses.
334
335Note: If `false`, error responses are considered successful and the request will not be retried.
336
337##### onDownloadProgress
338
339Type: `Function`
340
341Download progress event handler.
342
343The function receives a `progress` and `chunk` argument:
344- The `progress` object contains the following elements: `percent`, `transferredBytes` and `totalBytes`. If it's not possible to retrieve the body size, `totalBytes` will be `0`.
345- The `chunk` argument is an instance of `Uint8Array`. It's empty for the first call.
346
347```js
348import ky from 'ky';
349
350const response = await ky('https://example.com', {
351 onDownloadProgress: (progress, chunk) => {
352 // Example output:
353 // `0% - 0 of 1271 bytes`
354 // `100% - 1271 of 1271 bytes`
355 console.log(`${progress.percent * 100}% - ${progress.transferredBytes} of ${progress.totalBytes} bytes`);
356 }
357});
358```
359
360##### parseJson
361
362Type: `Function`\
363Default: `JSON.parse()`
364
365User-defined JSON-parsing function.
366
367Use-cases:
3681. Parse JSON via the [`bourne` package](https://github.com/hapijs/bourne) to protect from prototype pollution.
3692. Parse JSON with [`reviver` option of `JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).
370
371```js
372import ky from 'ky';
373import bourne from '@hapijs/bourne';
374
375const json = await ky('https://example.com', {
376 parseJson: text => bourne(text)
377}).json();
378```
379
380##### fetch
381
382Type: `Function`\
383Default: `fetch`
384
385User-defined `fetch` function.
386Has to be fully compatible with the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) standard.
387
388Use-cases:
3891. Use custom `fetch` implementations like [`isomorphic-unfetch`](https://www.npmjs.com/package/isomorphic-unfetch).
3902. Use the `fetch` wrapper function provided by some frameworks that use server-side rendering (SSR).
391
392```js
393import ky from 'ky';
394import fetch from 'isomorphic-unfetch';
395
396const json = await ky('https://example.com', {fetch}).json();
397```
398
399### ky.extend(defaultOptions)
400
401Create a new `ky` instance with some defaults overridden with your own.
402
403In contrast to `ky.create()`, `ky.extend()` inherits defaults from its parent.
404
405You can pass headers as a `Headers` instance or a plain object.
406
407You can remove a header with `.extend()` by passing the header with an `undefined` value.
408Passing `undefined` as a string removes the header only if it comes from a `Headers` instance.
409
410```js
411import ky from 'ky';
412
413const url = 'https://sindresorhus.com';
414
415const original = ky.create({
416 headers: {
417 rainbow: 'rainbow',
418 unicorn: 'unicorn'
419 }
420});
421
422const extended = original.extend({
423 headers: {
424 rainbow: undefined
425 }
426});
427
428const response = await extended(url).json();
429
430console.log('rainbow' in response);
431//=> false
432
433console.log('unicorn' in response);
434//=> true
435```
436
437### ky.create(defaultOptions)
438
439Create a new Ky instance with complete new defaults.
440
441```js
442import ky from 'ky';
443
444// On https://my-site.com
445
446const api = ky.create({prefixUrl: 'https://example.com/api'});
447
448const response = await api.get('users/123');
449//=> 'https://example.com/api/users/123'
450
451const response = await api.get('/status', {prefixUrl: ''});
452//=> 'https://my-site.com/status'
453```
454
455#### defaultOptions
456
457Type: `object`
458
459### ky.stop
460
461A `Symbol` that can be returned by a `beforeRetry` hook to stop the retry. This will also short circuit the remaining `beforeRetry` hooks.
462
463Note: 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/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.
464
465A 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.
466
467```js
468import ky from 'ky';
469
470const options = {
471 hooks: {
472 beforeRetry: [
473 async ({request, options, error, retryCount}) => {
474 const shouldStopRetry = await ky('https://example.com/api');
475 if (shouldStopRetry) {
476 return ky.stop;
477 }
478 }
479 ]
480 }
481};
482
483// Note that response will be `undefined` in case `ky.stop` is returned.
484const response = await ky.post('https://example.com', options);
485
486// Using `.text()` or other body methods is not supported.
487const text = await ky('https://example.com', options).text();
488```
489
490### HTTPError
491
492Exposed for `instanceof` checks. The error has a `response` property with the [`Response` object](https://developer.mozilla.org/en-US/docs/Web/API/Response), `request` property with the [`Request` object](https://developer.mozilla.org/en-US/docs/Web/API/Request), and `options` property with normalized options (either passed to `ky` when creating an instance with `ky.create()` or directly when performing the request).
493
494### TimeoutError
495
496The error thrown when the request times out. It has a `request` property with the [`Request` object](https://developer.mozilla.org/en-US/docs/Web/API/Request).
497
498## Tips
499
500### Sending form data
501
502Sending form data in Ky is identical to `fetch`. Just pass a [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) instance to the `body` option. The `Content-Type` header will be automatically set to `multipart/form-data`.
503
504```js
505import ky from 'ky';
506
507// `multipart/form-data`
508const formData = new FormData();
509formData.append('food', 'fries');
510formData.append('drink', 'icetea');
511
512const response = await ky.post(url, {body: formData});
513```
514
515If you want to send the data in `application/x-www-form-urlencoded` format, you will need to encode the data with [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams).
516
517```js
518import ky from 'ky';
519
520// `application/x-www-form-urlencoded`
521const searchParams = new URLSearchParams();
522searchParams.set('food', 'fries');
523searchParams.set('drink', 'icetea');
524
525const response = await ky.post(url, {body: searchParams});
526```
527
528### Setting a custom `Content-Type`
529
530Ky automatically sets an appropriate [`Content-Type`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/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.
531
532```js
533import ky from 'ky';
534
535const json = await ky.post('https://example.com', {
536 headers: {
537 'content-type': 'application/json'
538 }
539 json: {
540 foo: true
541 },
542}).json();
543
544console.log(json);
545//=> `{data: '🦄'}`
546```
547
548### Cancellation
549
550Fetch (and hence Ky) has built-in support for request cancellation through the [`AbortController` API](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). [Read more.](https://developers.google.com/web/updates/2017/09/abortable-fetch)
551
552Example:
553
554```js
555import ky from 'ky';
556
557const controller = new AbortController();
558const {signal} = controller;
559
560setTimeout(() => {
561 controller.abort();
562}, 5000);
563
564try {
565 console.log(await ky(url, {signal}).text());
566} catch (error) {
567 if (error.name === 'AbortError') {
568 console.log('Fetch aborted');
569 } else {
570 console.error('Fetch error:', error);
571 }
572}
573```
574
575## FAQ
576
577#### How do I use this in Node.js?
578
579Check out [`ky-universal`](https://github.com/sindresorhus/ky-universal#faq).
580
581#### How do I use this with a web app (React, Vue.js, etc.) that uses server-side rendering (SSR)?
582
583Check out [`ky-universal`](https://github.com/sindresorhus/ky-universal#faq).
584
585#### How do I test a browser library that uses this?
586
587Either use a test runner that can run in the browser, like Mocha, or use [AVA](https://avajs.dev) with `ky-universal`. [Read more.](https://github.com/sindresorhus/ky-universal#faq)
588
589#### How do I use this without a bundler like Webpack?
590
591Make 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.
592
593```html
594<script type="module">
595import ky from 'https://unpkg.com/ky/distribution/index.js';
596
597const json = await ky('https://jsonplaceholder.typicode.com/todos/1').json();
598
599console.log(json.title);
600//=> 'delectus aut autem
601</script>
602```
603
604#### How is it different from [`got`](https://github.com/sindresorhus/got)
605
606See my answer [here](https://twitter.com/sindresorhus/status/1037406558945042432). Got is maintained by the same people as Ky.
607
608#### How is it different from [`axios`](https://github.com/axios/axios)?
609
610See my answer [here](https://twitter.com/sindresorhus/status/1037763588826398720).
611
612#### How is it different from [`r2`](https://github.com/mikeal/r2)?
613
614See my answer in [#10](https://github.com/sindresorhus/ky/issues/10).
615
616#### What does `ky` mean?
617
618It's just a random short npm package name I managed to get. It does, however, have a meaning in Japanese:
619
620> 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.
621
622## Browser support
623
624The latest version of Chrome, Firefox, and Safari.
625
626## Node.js support
627
628Polyfill the needed browser globals or just use [`ky-universal`](https://github.com/sindresorhus/ky-universal).
629
630## Related
631
632- [ky-universal](https://github.com/sindresorhus/ky-universal) - Use Ky in both Node.js and browsers
633- [got](https://github.com/sindresorhus/got) - Simplified HTTP requests for Node.js
634- [ky-hooks-change-case](https://github.com/alice-health/ky-hooks-change-case) - Ky hooks to modify cases on requests and responses of objects
635
636## Maintainers
637
638- [Sindre Sorhus](https://github.com/sindresorhus)
639- [Szymon Marczak](https://github.com/szmarczak)
640- [Seth Holladay](https://github.com/sholladay)