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
Provenance
- Commit
7f2eade- Tree
6a6327f- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
7d23d68
12 files changed+251 added−38 removed
modified:source/core/constants.ts+3 added-3 removed
97 unmodified lines98 99 @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 lines129 code: 'BACKUP_ENDPOINT'130 });131 132 // 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 lines172 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();177 178 // Simple retry with default delay179 if (data.error?.code === 'TEMPORARY_ERROR') {180 return ky.retry();109 unmodified linesmodified:source/errors/HTTPError.ts+5 added-1 removed
4 unmodified lines567899101112131415161717 unmodified lines4 unmodified lines
/**Error thrown when the response has a non-2xx status code and `throwHttpErrors` is enabled.
The error has a `response` property with the `Response` object, a `request` property with the `Request` object, an `options` property with the normalized options, and a `data` property with the pre-parsed response body. The response body is automatically consumed when populating `data`, so `response.json()` and other body methods will not work. Use `data` instead.The error has a `response` property with the `Response` object, a `request` property with the `Request` object, an `options` property with the normalized options (either passed to `ky` when creating an instance with `ky.create()` or directly when performing the request), and a `data` property with the pre-parsed response body. For JSON responses (based on `Content-Type`), the body is parsed using the `parseJson` option if set, or `JSON.parse` by default. For other content types, it is set as plain text. If the body is empty or parsing fails, `data` will be `undefined`. To avoid hanging or excessive buffering, `error.data` population is bounded by the request timeout and a 10 MiB response body size limit. The `data` property is populated before `beforeError` hooks run, so hooks can access it.
The response body is automatically consumed when populating `error.data`, so `error.response.json()` and other body methods will not work. Use `error.data` instead. The `error.response` object is still available for headers, status, etc.
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 be an instance of `NetworkError` instead of `HTTPError` and will not contain a `response` property.*/export class HTTPError<T = unknown> extends KyError { override name = 'HTTPError' as const; response: KyResponse<T>;17 unmodified linesmodified:source/errors/KyError.ts+4 added
123456789104 unmodified lines/**Base class for all Ky-specific errors. `HTTPError`, `NetworkError`, `TimeoutError`, and `ForceRetryError` extend this class.
You can use `instanceof KyError` to check if an error originated from Ky, or use the `isKyError()` type guard for cross-realm compatibility and TypeScript type narrowing.
Note: `SchemaValidationError` is intentionally not considered a Ky error. `KyError` covers failures in Ky's HTTP lifecycle (bad status, timeout, retry), while schema validation errors originate from the user-provided schema, not from Ky itself.*/export class KyError extends Error { override name = 'KyError';
4 unmodified linesmodified:source/errors/NetworkError.ts+4 added-2 removed
12345567789101112136 unmodified linesimport type {KyRequest} from '../types/request.js';import {KyError} from './KyError.js';
/**Error thrown when a network error occurs during the request (e.g., DNS failure, connection refused, offline).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. The original error is available via the standard `cause` property.
The error has a `request` property with the `Request` object. The original error is available via the standard `cause` property.Network errors are automatically retried (for retriable methods).
Note: Network errors are detected using runtime-specific heuristics. Unrecognized runtimes may produce errors that are not wrapped in `NetworkError`. Use the `shouldRetry` option to handle such cases.*/export class NetworkError extends KyError { override name = 'NetworkError' as const; request: KyRequest;6 unmodified linesmodified:source/errors/SchemaValidationError.ts+1 added-1 removed
12344567825 unmodified linesimport type {StandardSchemaV1Issue} from '../types/standard-schema.js';
/**Thrown when a response body fails validation against a user-provided Standard Schema.The error thrown when [Standard Schema](https://github.com/standard-schema/standard-schema) validation fails in `.json(schema)`. It has an `issues` property with the validation issues from the schema.
This error intentionally does not extend `KyError` because it does not represent a failure in Ky's HTTP lifecycle. The request succeeded; the user's schema rejected the data. As such, it is not matched by `isKyError()`.
@example25 unmodified linesmodified:source/errors/TimeoutError.ts+1 added-3 removed
1234567567896 unmodified linesimport type {KyRequest} from '../types/request.js';import {KyError} from './KyError.js';
/**Error thrown when the request times out.
The error has a `request` property with the `Request` object.Error thrown when the request times out. It has a `request` property with the `Request` object.*/export class TimeoutError extends KyError { override name = 'TimeoutError' as const; request: KyRequest;6 unmodified linesmodified:source/types/hooks.ts+1 added-1 removed
331 unmodified lines332 333 // 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 linesmodified:source/types/ky.ts+10 added-2 removed
68 unmodified lines69 */70 head: (url: Input, options?: Options) => ResponsePromise;71 72 /**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.74 75 @returns A new Ky instance.76 */77 create: (defaultOptions?: Options) => KyInstance;2 unmodified lines80 Create a new Ky instance with some defaults overridden with your own.81 82 In contrast to `ky.create()`, `ky.extend()` inherits defaults from its parent.83 84+ You can pass headers as a `Headers` instance or a plain object.85+86+ 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.87+88+ Similarly, you can remove existing `hooks` entries by extending the hook with an explicit `undefined`.89+90+ 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.91+92 You can also refer to parent defaults by providing a function to `.extend()`.93 94 @example95 ```61 unmodified lines157 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();162 163 // Simple retry with default delay164 if (data.error?.code === 'TEMPORARY_ERROR') {165 return ky.retry();29 unmodified linesmodified:source/types/options.ts+14 added-5 removed
12 unmodified lines13 14 export type Input = string | URL | Request;15 16 export type Progress = {17+ /**18+ A number between `0` and `1` representing the progress percentage.19+ */20 percent: number;21+22+ /**23+ The number of bytes transferred so far.24+ */25 transferredBytes: number;26 27 /**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 lines167 */168 prefix?: URL | string;169 170 /**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.172 173 If `retry` is a number, it will be used as `limit` and other defaults will remain in place.174 175 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.176 177 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.178 172- 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`.180 181 @example182 ```183 import ky from 'ky';42 unmodified lines226 */227 totalTimeout?: number | false;228 229 /**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;233 234 /**144 unmodified lines379 });380 // Result: {a: 1, b: {updated: true}, c: 3}381 // Note: The original `b.nested` is gone (shallow merge)382 ```383+384+ @default {}385 */386 context?: Record<string, unknown>;387 };388 19 unmodified lines408 HTTP headers used to make the request.409 410 You can pass a `Headers` instance or a plain object.411 403- 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.413 414 @example415 ```416 import ky from 'ky';58 unmodified linesmodified:source/types/retry.ts+5 added-1 removed
63 unmodified lines64 */65 backoffLimit?: number;66 67 /**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).69 70 @default attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 100071 */72 delay?: (attemptCount: number) => number;6 unmodified lines79 Set to `true` to use full jitter, which randomizes the delay between 0 and the computed delay.80 81 Alternatively, pass a function to implement custom jitter strategies.82 83+ Note: Jitter is not applied when the server provides a `Retry-After` header, as the server's explicit timing should be respected.84+85 @default undefined (no jitter)86 87 @example88 ```49 unmodified lines138 - `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.141 142+ @default undefined143+144 @example145 ```146 import ky, {HTTPError} from 'ky';147 28 unmodified linesmodified:source/utils/merge.ts+1 added-1 removed
25 unmodified lines26 value,27 };28 29 /**30-Wraps a value so that `ky.extend()` will replace the parent value instead of merging with it.30+Wraps 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.31 32 By 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.33 34 @example271 unmodified linesmodified:readme.md+202 added-18 removed
46 unmodified lines47 - 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`)57 58 ## Install59 181 unmodified lines241 const response = await ky('/users', {baseUrl: '/api/'});242 //=> 'https://example.com/users'243 ```244 245+See [FAQ: `baseUrl` vs `prefix`](#baseurl-vs-prefix)246+247 ##### prefix248 249 Type: `string | URL`250 2 unmodified lines253 Useful when used with [`ky.extend()`](#kyextenddefaultoptions) to create niche-specific Ky instances.254 255 *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.*256 257+See [FAQ: `baseUrl` vs `prefix`](#baseurl-vs-prefix)258+259 ```js260 import ky from 'ky';261 262 // On https://example.com16 unmodified lines279 - `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`289 284-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.290+Controls retry behavior. Each field is documented individually below.291 292 If `retry` is a number, it will be used as `limit` and other defaults will remain in place.293 294 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.295 296 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.297 292-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`.298+If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will use `maxRetryAfter`.299 300 The `backoffLimit` option is the upper limit of the delay per retry in milliseconds.301 To clamp the delay, set `backoffLimit` to 1000, for example.302 By default, the delay is calculated with `0.3 * (2 ** (attemptCount - 1)) * 1000`. The delay increases exponentially.303 298-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`.304+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`, and must return the delay in milliseconds.305 306 The `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.307 308 **Note:** Jitter is not applied when the server provides a `Retry-After` header, as the server's explicit timing should be respected.377 unmodified lines686 687 // 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 lines733 Download progress event handler.734 735 The 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.741 742 ```js743 import ky from 'ky';744 17 unmodified lines762 > 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.763 764 The 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.770 771 ```js772 import ky from 'ky';245 unmodified lines1018 ```1019 1020 ### ky.create(defaultOptions)1021 1016-Create a new Ky instance with complete new defaults.1022+Create a new Ky instance with complete new defaults, without inheriting from any parent instance.1023 1024 ```js1025 import ky from 'ky';1026 81 unmodified lines1108 Original 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.1109 1110 ```js1111 try {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 lines1139 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();1144 1145 // Simple retry with default delay1146 if (data.error?.code === 'TEMPORARY_ERROR') {1147 return ky.retry();149 unmodified lines1297 ### TimeoutError1298 1299 The 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).1300 1301+```js1302+import ky, {isTimeoutError} from 'ky';1303+1304+try {1305+ await ky('https://example.com').json();1306+} catch (error) {1307+ if (isTimeoutError(error)) {1308+ console.log('Request timed out');1309+ }1310+}1311+```1312+1313 ### NetworkError1314 1315 The 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 lines1417 import ky from 'ky';1418 1419 const 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 lines1636 Node.js supports `fetch` natively, so you can just use this package directly.1637 1638 #### How do I use this with a web app (React, Vue.js, etc.) that uses server-side rendering (SSR)?1639 1622-Same as above.1640+Node.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`:1641 1642+```js1643+const api = ky.create({1644+ baseUrl: globalThis.window === undefined1645+ ? (process.env.BASE_URL ?? 'http://localhost:3000')1646+ : undefined,1647+});1648+```1649+1650+<a name="baseurl-vs-prefix"></a>1651+#### What's the difference between `baseUrl` and `prefix`?1652+1653+**`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.1654+1655+**`prefix`** does plain string joining before URL resolution. The leading slash on the input is stripped, so it always appends to the prefix regardless.1656+1657+Use `baseUrl` in almost all cases. Use `prefix` only when you want origin-relative inputs like `/users` to be treated as page-relative.1658+1659+```js1660+// On https://example.com1661+1662+// baseUrl: standard URL resolution1663+ky('users', {baseUrl: '/api/'});1664+//=> https://example.com/api/users1665+1666+ky('/users', {baseUrl: '/api/'});1667+//=> https://example.com/users ← leading slash wins1668+1669+1670+// prefix: always appends1671+ky('users', {prefix: '/api'});1672+//=> https://example.com/api/users1673+1674+ky('/users', {prefix: '/api'});1675+//=> https://example.com/api/users ← leading slash ignored1676+```1677+1678 #### How do I test a browser library that uses this?1679 1680 Use a test runner that can run in the browser, like [Vitest](https://vitest.dev/guide/browser/) or [Playwright](https://playwright.dev).1681 1682+#### How do I add authentication headers to every request?1683+1684+Use the [`beforeRequest` hook](#hooksbeforerequest) to attach headers before each request:1685+1686+```js1687+const api = ky.create({1688+ hooks: {1689+ beforeRequest: [1690+ ({request}) => {1691+ request.headers.set('Authorization', `Bearer ${getToken()}`);1692+ }1693+ ]1694+ }1695+});1696+```1697+1698+#### How do I implement token refresh on 401 responses?1699+1700+Configure `retry` to retry on 401, then use the [`beforeRetry` hook](#hooksbeforeretry) to refresh the token:1701+1702+```js1703+const 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+```1715+1716+#### How do I mock Ky in tests?1717+1718+Use [MSW](https://mswjs.io) to intercept requests at the network level without modifying your code. Alternatively, pass a custom `fetch` to your Ky instance:1719+1720+```js1721+const api = ky.create({1722+ fetch: async () => new Response(JSON.stringify({name: 'Test'}), {1723+ headers: {1724+ 'Content-Type': 'application/json'1725+ },1726+ }),1727+});1728+```1729+1730+#### How do I retry based on the response body?1731+1732+Use [`ky.retry()`](#kyretryoptions) in an [`afterResponse`](#hooksafterresponse) hook. This lets you force a retry even when the status code is 2xx:1733+1734+```js1735+import ky from 'ky';1736+1737+const response = await ky('https://example.com', {1738+ hooks: {1739+ afterResponse: [1740+ async ({response}) => {1741+ const data = await response.json();1742+1743+ if (data.status === 'pending') {1744+ return ky.retry();1745+ }1746+ }1747+ ]1748+ }1749+});1750+```1751+1752+The retry respects `retry.limit` and is observable in `beforeRetry` hooks.1753+1754+#### How do I stop retrying early?1755+1756+Throw from a `beforeRetry` hook to stop retrying and propagate the error, or return [`ky.stop`](#kystop) to stop silently (the request resolves with `undefined`):1757+1758+```js1759+import ky, {isHTTPError} from 'ky';1760+1761+const 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+```1773+1774+#### How do I only throw on certain HTTP errors?1775+1776+For simple status-based filtering, pass a function to `throwHttpErrors`:1777+1778+```js1779+import ky from 'ky';1780+1781+// Only throw on 5xx errors; 4xx responses are returned normally1782+const api = ky.create({1783+ throwHttpErrors: status => status >= 500,1784+});1785+1786+const response = await api('https://example.com/resource');1787+1788+if (response.status === 404) {1789+ // Handle "not found" as normal app flow1790+}1791+```1792+1793+If you need to access the response body in the non-throwing path, use `throwHttpErrors: false` and throw manually in an [`afterResponse`](#hooksafterresponse) hook:1794+1795+```js1796+import ky, {HTTPError} from 'ky';1797+1798+const 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+```1811+1812 #### How do I use this without a bundler like Webpack?1813 1814 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.1815 43 unmodified lines