Skip to content
Myr

Readme tweaks

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sindre Sorhus · committed by Sindre Sorhus · parent 7d23d68 · Browse files · 12 files+251 added−38 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

12 files+251 added−38 removed

  • other:+251 added−38 removed

12 files+251 added−38 removed

modified:source/core/constants.ts+3 added-3 removed
97 unmodified lines
9899 @example100 ```101 try {102 const data = await response.clone().json();102 const data = await response.json();103 validateBusinessLogic(data);104 } catch (error) {105 return ky.retry({106 code: 'VALIDATION_FAILED',
22 unmodified lines
129 code: 'BACKUP_ENDPOINT'130 });131132 // Retry with refreshed authentication token133 const data = await response.clone().json();133 const data = await response.json();134 return ky.retry({135 request: new Request(request, {136 headers: {137 ...Object.fromEntries(request.headers),
34 unmodified lines
172 afterResponse: [173 async ({request, response}) => {174 // Retry based on response body content175 if (response.status === 200) {176 const data = await response.clone().json();176 const data = await response.json();177178 // Simple retry with default delay179 if (data.error?.code === 'TEMPORARY_ERROR') {180 return ky.retry();
109 unmodified lines
modified:source/errors/HTTPError.ts+5 added-1 removed
modified:source/errors/KyError.ts+4 added
modified:source/errors/NetworkError.ts+4 added-2 removed
modified:source/errors/SchemaValidationError.ts+1 added-1 removed
modified:source/errors/TimeoutError.ts+1 added-3 removed
modified:source/types/hooks.ts+1 added-1 removed
331 unmodified lines
332333 // Or force retry based on response body content334 async ({response}) => {335 if (response.status === 200) {336 const data = await response.clone().json();336 const data = await response.json();337 if (data.error?.code === 'RATE_LIMIT') {338 // Retry with custom delay from API response339 return ky.retry({340 delay: data.error.retryAfter * 1000,
21 unmodified lines
modified:source/types/ky.ts+10 added-2 removed
68 unmodified lines
69 */70 head: (url: Input, options?: Options) => ResponsePromise;7172 /**73 Create a new Ky instance with complete new defaults.73 Create a new Ky instance with complete new defaults, without inheriting from any parent instance.7475 @returns A new Ky instance.76 */77 create: (defaultOptions?: Options) => KyInstance;
2 unmodified lines
80 Create a new Ky instance with some defaults overridden with your own.8182 In contrast to `ky.create()`, `ky.extend()` inherits defaults from its parent.8384 You can pass headers as a `Headers` instance or a plain object.8586 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.8788 Similarly, you can remove existing `hooks` entries by extending the hook with an explicit `undefined`.8990 By default, `.extend()` deep-merges options: hooks are appended, headers are merged, and search parameters are accumulated. Use `replaceOption` when you want to fully replace a merged property instead.9192 You can also refer to parent defaults by providing a function to `.extend()`.9394 @example95 ```
61 unmodified lines
157 afterResponse: [158 async ({response}) => {159 // Retry based on response body content160 if (response.status === 200) {153 const data = await response.clone().json();161 const data = await response.json();162163 // Simple retry with default delay164 if (data.error?.code === 'TEMPORARY_ERROR') {165 return ky.retry();
29 unmodified lines
modified:source/types/options.ts+14 added-5 removed
12 unmodified lines
1314export type Input = string | URL | Request;1516export type Progress = {17 /**18 A number between `0` and `1` representing the progress percentage.19 */20 percent: number;2122 /**23 The number of bytes transferred so far.24 */25 transferredBytes: number;2627 /**21 Note: If it's not possible to retrieve the body size, it will be `0`.28 The total number of bytes to be transferred. This is an estimate and may be `0` if the total size cannot be determined.29 */30 totalBytes: number;31};32
134 unmodified lines
167 */168 prefix?: URL | string;169170 /**164 An object representing `limit`, `methods`, `statusCodes`, `afterStatusCodes`, `maxRetryAfter`, `backoffLimit`, `delay`, `jitter`, `retryOnTimeout`, and `shouldRetry` fields for maximum retry count, allowed methods, allowed status codes, status codes allowed to use the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time, backoff limit, delay calculation function, retry jitter, timeout retry behavior, and custom retry logic.171 Controls retry behavior. Each field is documented in the `RetryOptions` type.172173 If `retry` is a number, it will be used as `limit` and other defaults will remain in place.174175 Network errors (e.g., DNS failures, connection refused, offline) are automatically retried for retriable methods. Only errors recognized as network errors are retried; other errors (e.g., programming bugs) are thrown immediately. Use `shouldRetry` to customize this behavior.176177 If the response provides an HTTP status contained in `afterStatusCodes`, Ky will wait until the date, timeout, or timestamp given in the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header has passed to retry the request. If `Retry-After` is missing, the non-standard [`RateLimit-Reset`](https://www.ietf.org/archive/id/draft-polli-ratelimit-headers-05.html#section-3.3) header is used in its place as a fallback. If the provided status code is not in the list, the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header will be ignored.178172 If `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 use `maxRetryAfter`.179 If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will use `maxRetryAfter`.180181 @example182 ```183 import ky from 'ky';
42 unmodified lines
226 */227 totalTimeout?: number | false;228229 /**223 Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially.230 Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially, unless otherwise noted.231 */232 hooks?: Hooks;233234 /**
144 unmodified lines
379 });380 // Result: {a: 1, b: {updated: true}, c: 3}381 // Note: The original `b.nested` is gone (shallow merge)382 ```383384 @default {}385 */386 context?: Record<string, unknown>;387};388
19 unmodified lines
408 HTTP headers used to make the request.409410 You can pass a `Headers` instance or a plain object.411403 You can remove a header with `.extend()` by passing the header with an `undefined` value.412 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.413414 @example415 ```416 import ky from 'ky';
58 unmodified lines
modified:source/types/retry.ts+5 added-1 removed
63 unmodified lines
64 */65 backoffLimit?: number;6667 /**68 A function to calculate the delay between retries given `attemptCount` (starts from 1).68 A function to calculate the delay in milliseconds between retries given `attemptCount` (starts from 1).6970 @default attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 100071 */72 delay?: (attemptCount: number) => number;
6 unmodified lines
79 Set to `true` to use full jitter, which randomizes the delay between 0 and the computed delay.8081 Alternatively, pass a function to implement custom jitter strategies.8283 Note: Jitter is not applied when the server provides a `Retry-After` header, as the server's explicit timing should be respected.8485 @default undefined (no jitter)8687 @example88 ```
49 unmodified lines
138 - `true` to force a retry (bypasses `retryOnTimeout`, status code checks, and other validations)139 - `false` to prevent a retry (no retry will occur)140 - `undefined` to use the default retry logic (`retryOnTimeout`, status codes, network errors). Unrecognized error types are not retried.141142 @default undefined143144 @example145 ```146 import ky, {HTTPError} from 'ky';147
28 unmodified lines
modified:source/utils/merge.ts+1 added-1 removed
25 unmodified lines
26 value,27 };2829/**30Wraps a value so that `ky.extend()` will replace the parent value instead of merging with it.30Wraps a value so that `ky.extend()` will replace the parent value instead of merging with it. Works with hooks, headers, search parameters, context, and any other deep-merged option.3132By default, `.extend()` deep-merges options with the parent instance: hooks get appended, headers get merged, and search parameters get accumulated. Use `replaceOption` when you want to fully replace a merged property instead.3334@example
271 unmodified lines
modified:readme.md+202 added-18 removed
46 unmodified lines
47- Treats non-2xx status codes as errors (after redirects)48- Retries failed requests49- JSON option50- Timeout support51- Upload and download progress52- Base URL option53- Instances with custom defaults54- Hooks55- Response validation with [Standard Schema](https://standardschema.dev) (Zod, Valibot, etc.)56- TypeScript niceties (e.g., `.json()` supports generics and defaults to `unknown`, not `any`)5758## Install59
181 unmodified lines
241const response = await ky('/users', {baseUrl: '/api/'});242//=> 'https://example.com/users'243```244245See [FAQ: `baseUrl` vs `prefix`](#baseurl-vs-prefix)246247##### prefix248249Type: `string | URL`250
2 unmodified lines
253Useful when used with [`ky.extend()`](#kyextenddefaultoptions) to create niche-specific Ky instances.254255*In most cases, you should use the `baseUrl` option instead, as it is more consistent with web standards. However, `prefix` is useful if you want origin-relative `input` URLs, such as `/users`, to be treated as if they were page-relative. In other words, the leading slash of the `input` will essentially be ignored, because the `prefix` will become part of the `input` before URL resolution happens.*256257See [FAQ: `baseUrl` vs `prefix`](#baseurl-vs-prefix)258259```js260import ky from 'ky';261262// On https://example.com
16 unmodified lines
279- `limit`: `2`280- `methods`: `get` `put` `head` `delete` `options` `trace`281- `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)282- `afterStatusCodes`: [`413`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/413), [`429`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429), [`503`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503)277- `maxRetryAfter`: `undefined`278- `backoffLimit`: `undefined`283- `maxRetryAfter`: `Infinity`284- `backoffLimit`: `Infinity`285- `delay`: `attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000`286- `jitter`: `undefined`287- `retryOnTimeout`: `false`288- `shouldRetry`: `undefined`289284An object representing `limit`, `methods`, `statusCodes`, `afterStatusCodes`, `maxRetryAfter`, `backoffLimit`, `delay`, `jitter`, `retryOnTimeout`, and `shouldRetry` fields for maximum retry count, allowed methods, allowed status codes, status codes allowed to use the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time, backoff limit, delay calculation function, retry jitter, timeout retry behavior, and custom retry logic.290Controls retry behavior. Each field is documented individually below.291292If `retry` is a number, it will be used as `limit` and other defaults will remain in place.293294Network errors (e.g., DNS failures, connection refused, offline) are automatically retried for retriable methods. Only errors recognized as network errors are retried; other errors (e.g., programming bugs) are thrown immediately. Use `shouldRetry` to customize this behavior.295296If the response provides an HTTP status contained in `afterStatusCodes`, Ky will wait until the date, timeout, or timestamp given in the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header has passed to retry the request. If `Retry-After` is missing, the non-standard [`RateLimit-Reset`](https://www.ietf.org/archive/id/draft-polli-ratelimit-headers-05.html#section-3.3) header is used in its place as a fallback. If the provided status code is not in the list, the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header will be ignored.297292If `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 use `maxRetryAfter`.298If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will use `maxRetryAfter`.299300The `backoffLimit` option is the upper limit of the delay per retry in milliseconds.301To clamp the delay, set `backoffLimit` to 1000, for example.302By default, the delay is calculated with `0.3 * (2 ** (attemptCount - 1)) * 1000`. The delay increases exponentially.303298The `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`.304The `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`, and must return the delay in milliseconds.305306The `jitter` option adds random jitter to retry delays to prevent thundering herd problems. When many clients retry simultaneously (e.g., after hitting a rate limit), they can overwhelm the server again. Jitter adds randomness to break this synchronization. Set to `true` to use full jitter, which randomizes the delay between 0 and the computed delay. Alternatively, pass a function to implement custom jitter strategies.307308**Note:** Jitter is not applied when the server provides a `Retry-After` header, as the server's explicit timing should be respected.
377 unmodified lines
686687 // Or force retry based on response body content688 async ({response}) => {689 if (response.status === 200) {684 const data = await response.clone().json();690 const data = await response.json();691 if (data.error?.code === 'RATE_LIMIT') {692 // Retry with custom delay from API response693 return ky.retry({694 delay: data.error.retryAfter * 1000,
38 unmodified lines
733Download progress event handler.734735The function receives these arguments:736- `progress` is an object with these properties:731- - `percent` is a number between 0 and 1 representing the progress percentage.732- - `transferredBytes` is the number of bytes transferred so far.733- - `totalBytes` is the total number of bytes to be transferred. This is an estimate and may be 0 if the total size cannot be determined.734- `chunk` is an instance of `Uint8Array` containing the data that was sent. Note: It's empty for the first call.737 - `percent` is a number between 0 and 1 representing the progress percentage.738 - `transferredBytes` is the number of bytes transferred so far.739 - `totalBytes` is the total number of bytes to be transferred. This is an estimate and may be 0 if the total size cannot be determined.740- `chunk` is an instance of `Uint8Array` containing the data that was received. Note: It's empty for the first call.741742```js743import ky from 'ky';744
17 unmodified lines
762> Requires [request stream support](https://caniuse.com/wf-fetch-request-streams) and HTTP/2 for HTTPS connections (in Chromium-based browsers). In unsupported environments, this handler is silently ignored.763764The function receives these arguments:765- `progress` is an object with these properties:760- - `percent` is a number between 0 and 1 representing the progress percentage.761- - `transferredBytes` is the number of bytes transferred so far.762- - `totalBytes` is the total number of bytes to be transferred. This is an estimate and may be 0 if the total size cannot be determined.766 - `percent` is a number between 0 and 1 representing the progress percentage.767 - `transferredBytes` is the number of bytes transferred so far.768 - `totalBytes` is the total number of bytes to be transferred. This is an estimate and may be 0 if the total size cannot be determined.769- `chunk` is an instance of `Uint8Array` containing the data that was sent. Note: It's empty for the last call.770771```js772import ky from 'ky';
245 unmodified lines
1018```10191020### ky.create(defaultOptions)10211016Create a new Ky instance with complete new defaults.1022Create a new Ky instance with complete new defaults, without inheriting from any parent instance.10231024```js1025import ky from 'ky';1026
81 unmodified lines
1108Original error that caused the retry. This allows you to preserve the error chain when forcing a retry based on caught exceptions. The error will be set as the `cause` of the `ForceRetryError`, enabling proper error chain traversal.11091110```js1111try {1106 const data = await response.clone().json();1112 const data = await response.json();1113 validateBusinessLogic(data);1114} catch (error) {1115 return ky.retry({1116 code: 'VALIDATION_FAILED',
22 unmodified lines
1139 afterResponse: [1140 async ({request, response}) => {1141 // Retry based on response body content1142 if (response.status === 200) {1137 const data = await response.clone().json();1143 const data = await response.json();11441145 // Simple retry with default delay1146 if (data.error?.code === 'TEMPORARY_ERROR') {1147 return ky.retry();
149 unmodified lines
1297### TimeoutError12981299The 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).13001301```js1302import ky, {isTimeoutError} from 'ky';13031304try {1305 await ky('https://example.com').json();1306} catch (error) {1307 if (isTimeoutError(error)) {1308 console.log('Request timed out');1309 }1310}1311```13121313### NetworkError13141315The error thrown when a network error occurs during the request (e.g., DNS failure, connection refused, offline). It has a `request` property with the [`Request` object](https://developer.mozilla.org/en-US/docs/Web/API/Request). The original error is available via the standard `cause` property.1316
100 unmodified lines
1417import ky from 'ky';14181419const json = await ky.post('https://example.com', {1420 headers: {1403 'content-type': 'application/json'1421 'content-type': 'application/x-amz-json-1.1'1422 },1423 json: {1424 foo: true1425 },
210 unmodified lines
1636Node.js supports `fetch` natively, so you can just use this package directly.16371638#### How do I use this with a web app (React, Vue.js, etc.) that uses server-side rendering (SSR)?16391622Same as above.1640Node.js supports `fetch` natively, so you can use Ky directly. The main consideration is that server-side requests require absolute URLs, while client-side requests can use relative URLs. Handle this with a conditional `baseUrl`:16411642```js1643const api = ky.create({1644 baseUrl: globalThis.window === undefined1645 ? (process.env.BASE_URL ?? 'http://localhost:3000')1646 : undefined,1647});1648```16491650<a name="baseurl-vs-prefix"></a>1651#### What's the difference between `baseUrl` and `prefix`?16521653**`baseUrl`** follows standard URL resolution rules — the same behavior as `new URL(input, baseUrl)`. A leading slash on the input means origin-root, overriding any path in the base URL.16541655**`prefix`** does plain string joining before URL resolution. The leading slash on the input is stripped, so it always appends to the prefix regardless.16561657Use `baseUrl` in almost all cases. Use `prefix` only when you want origin-relative inputs like `/users` to be treated as page-relative.16581659```js1660// On https://example.com16611662// baseUrl: standard URL resolution1663ky('users', {baseUrl: '/api/'});1664//=> https://example.com/api/users16651666ky('/users', {baseUrl: '/api/'});1667//=> https://example.com/users ← leading slash wins166816691670// prefix: always appends1671ky('users', {prefix: '/api'});1672//=> https://example.com/api/users16731674ky('/users', {prefix: '/api'});1675//=> https://example.com/api/users ← leading slash ignored1676```16771678#### How do I test a browser library that uses this?16791680Use a test runner that can run in the browser, like [Vitest](https://vitest.dev/guide/browser/) or [Playwright](https://playwright.dev).16811682#### How do I add authentication headers to every request?16831684Use the [`beforeRequest` hook](#hooksbeforerequest) to attach headers before each request:16851686```js1687const api = ky.create({1688 hooks: {1689 beforeRequest: [1690 ({request}) => {1691 request.headers.set('Authorization', `Bearer ${getToken()}`);1692 }1693 ]1694 }1695});1696```16971698#### How do I implement token refresh on 401 responses?16991700Configure `retry` to retry on 401, then use the [`beforeRetry` hook](#hooksbeforeretry) to refresh the token:17011702```js1703const api = ky.create({1704 retry: {statusCodes: [401]},1705 hooks: {1706 beforeRetry: [1707 async ({request}) => {1708 const token = await refreshToken();1709 request.headers.set('Authorization', `Bearer ${token}`);1710 }1711 ]1712 }1713});1714```17151716#### How do I mock Ky in tests?17171718Use [MSW](https://mswjs.io) to intercept requests at the network level without modifying your code. Alternatively, pass a custom `fetch` to your Ky instance:17191720```js1721const api = ky.create({1722 fetch: async () => new Response(JSON.stringify({name: 'Test'}), {1723 headers: {1724 'Content-Type': 'application/json'1725 },1726 }),1727});1728```17291730#### How do I retry based on the response body?17311732Use [`ky.retry()`](#kyretryoptions) in an [`afterResponse`](#hooksafterresponse) hook. This lets you force a retry even when the status code is 2xx:17331734```js1735import ky from 'ky';17361737const response = await ky('https://example.com', {1738 hooks: {1739 afterResponse: [1740 async ({response}) => {1741 const data = await response.json();17421743 if (data.status === 'pending') {1744 return ky.retry();1745 }1746 }1747 ]1748 }1749});1750```17511752The retry respects `retry.limit` and is observable in `beforeRetry` hooks.17531754#### How do I stop retrying early?17551756Throw from a `beforeRetry` hook to stop retrying and propagate the error, or return [`ky.stop`](#kystop) to stop silently (the request resolves with `undefined`):17571758```js1759import ky, {isHTTPError} from 'ky';17601761const response = await ky('https://example.com', {1762 hooks: {1763 beforeRetry: [1764 ({error}) => {1765 if (isHTTPError(error) && error.response.status === 400) {1766 throw error; // Stop retrying, propagate the error1767 }1768 }1769 ]1770 }1771});1772```17731774#### How do I only throw on certain HTTP errors?17751776For simple status-based filtering, pass a function to `throwHttpErrors`:17771778```js1779import ky from 'ky';17801781// Only throw on 5xx errors; 4xx responses are returned normally1782const api = ky.create({1783 throwHttpErrors: status => status >= 500,1784});17851786const response = await api('https://example.com/resource');17871788if (response.status === 404) {1789 // Handle "not found" as normal app flow1790}1791```17921793If you need to access the response body in the non-throwing path, use `throwHttpErrors: false` and throw manually in an [`afterResponse`](#hooksafterresponse) hook:17941795```js1796import ky, {HTTPError} from 'ky';17971798const api = ky.create({1799 throwHttpErrors: false,1800 hooks: {1801 afterResponse: [1802 ({request, options, response}) => {1803 if (response.status >= 500) {1804 throw new HTTPError(response, request, options);1805 }1806 }1807 ]1808 }1809});1810```18111812#### How do I use this without a bundler like Webpack?18131814Make 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.1815
43 unmodified lines