readme.md
This file
Path
readme.md
1,958 lines · 73.6 KiB · Markdown
Last changed by
Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327
History of this fileTake it
The walk stopped after 200 commits: lines older than 37fc250 point at it.
Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1–7why, one step back1<div align="center">2 <br>3 <div>4 <img width="600" height="600" src="media/logo.svg" alt="ky">5 </div>6 <br>7 <br>Meta tweaksSindre Sorhusbefore adoptiond375014
line 8why, one step back8 <br>Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 9–28why, one step back9 <br>10</div>1112> Ky is a tiny and elegant HTTP client based on the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch)1314[](https://codecov.io/gh/sindresorhus/ky)15[](https://bundlephobia.com/result?p=ky)1617Ky targets [modern browsers](#browser-support), Node.js, Bun, and Deno.1819It's just a tiny package with no dependencies.2021## Benefits over plain `fetch`2223- Simpler API24- Method shortcuts (`ky.post()`)25- Treats non-2xx status codes as errors (after redirects)26- Retries failed requests27- JSON option28- Timeout supportReadme tweaksSindre Sorhusbefore adoption7f2eade
line 29why, one step back29- Upload and download progressAdd `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
line 30why, one step back30- Base URL optionAdd retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 31–32why, one step back31- Instances with custom defaults32- HooksReadme tweaksSindre Sorhusbefore adoption7f2eade
line 33why, one step back33- Response validation with [Standard Schema](https://standardschema.dev) (Zod, Valibot, etc.)Fix typosSindre Sorhusbefore adoptionbbc98fc
line 34why, one step back34- TypeScript niceties (e.g., `.json()` supports generics and defaults to `unknown`, not `any`)Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 35–41why, one step back3536## Install3738```sh39npm install ky40```41Add note about readme being dev versionSindre Sorhusbefore adoption7003a19
lines 42–44why, one step back42> [!NOTE]43> This readme is for the next version of Ky. For the current version, [click here](https://www.npmjs.com/package/ky).44Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 45–96why, one step back45###### CDN4647- [jsdelivr](https://cdn.jsdelivr.net/npm/ky/+esm)48- [unpkg](https://unpkg.com/ky)49- [esm.sh](https://esm.sh/ky)5051## Usage5253```js54import ky from 'ky';5556const json = await ky.post('https://example.com', {json: {foo: true}}).json();5758console.log(json);59//=> {data: '🦄'}60```6162With plain `fetch`, it would be:6364```js65class HTTPError extends Error {}6667const response = await fetch('https://example.com', {68 method: 'POST',69 body: JSON.stringify({foo: true}),70 headers: {71 'content-type': 'application/json'72 }73});7475if (!response.ok) {76 throw new HTTPError(`Fetch error: ${response.statusText}`);77}7879const json = await response.json();8081console.log(json);82//=> {data: '🦄'}83```8485If you are using [Deno](https://github.com/denoland/deno), import Ky from a URL. For example, using a CDN:8687```js88import ky from 'https://esm.sh/ky';89```9091## API9293### ky(input, options?)9495The `input` and `options` are the same as [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch), with additional `options` available (see below).96Allow `parseJson` to handle empty bodies (#877)Seth Holladaybefore adoption294fe63
line 97why, one step back97Returns 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/Fetch_API/Using_Fetch#body) 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`. Note that `.json()` will throw if the body is empty, as it cannot be parsed. However, you can use the `parseJson` option to add custom handling for empty bodies.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 98–100why, one step back9899Available body shortcuts: `.json()`, `.text()`, `.formData()`, `.arrayBuffer()`, `.blob()`, and `.bytes()`. The `.bytes()` shortcut is only present when the runtime supports `Response.prototype.bytes()`.100TweaksSindre Sorhusbefore adoption3ded2aa
lines 101–102why, one step back101Invalid options, an invalid `input`, and an error thrown by an `init` hook reject the returned promise instead of throwing, the same way `fetch()` reports them. They are not passed to `beforeError` hooks, because no request was made.102Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 103–123why, one step back103```js104import ky from 'ky';105106const user = await ky('/api/user').json();107108console.log(user);109```110111⌨️ **TypeScript:** Accepts an optional [type parameter](https://www.typescriptlang.org/docs/handbook/2/generics.html), which defaults to [`unknown`](https://www.typescriptlang.org/docs/handbook/2/functions.html#unknown), and is passed through to the return type of `.json()`.112113```ts114import ky from 'ky';115116// user1 is unknown117const user1 = await ky('/api/users/1').json();118// user2 is a User119const user2 = await ky<User>('/api/users/2').json();120// user3 is a User121const user3 = await ky('/api/users/3').json<User>();122123console.log([user1, user2, user3]);Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9
line 124why, one step back124```Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 125why, one step back125Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9
lines 126–144why, one step back126You can also get the response body as JSON and validate it with a Standard Schema compatible validator (for example, Zod 3.24+). This throws a `SchemaValidationError` when validation fails.127128```ts129import ky, {SchemaValidationError} from 'ky';130import {z} from 'zod';131132const userSchema = z.object({name: z.string()});133134try {135 const user = await ky('/api/user').json(userSchema);136 console.log(user.name);137} catch (error) {138 if (error instanceof SchemaValidationError) {139 console.error(error.issues);140 }141}142```143144```tsAdd retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 145–155why, one step back145// Get raw bytes (when supported by the runtime)146const bytes = await ky('/api/file').bytes();147console.log(bytes instanceof Uint8Array);148```149150### ky.get(input, options?)151### ky.post(input, options?)152### ky.put(input, options?)153### ky.patch(input, options?)154### ky.head(input, options?)155### ky.delete(input, options?)Add QUERY method support (#873)Sindre Sorhusbefore adoption6edddd9
line 156why, one step back156### ky.query(input, options?)Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 157–167why, one step back157158Sets `options.method` to the method name and makes a request.159160⌨️ **TypeScript:** Accepts an optional type parameter for use with JSON responses (see [`ky()`](#kyinput-options)).161162#### input163164Type: `string` | `URL` | `Request`165166Same as [`fetch` input](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#input).167TweaksSindre Sorhusbefore adoption830ab47
line 168why, one step back168When using a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) instance as `input`, the `prefix` and `baseUrl` options are ignored. The `searchParams` option still applies.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 169–182why, one step back169170#### options171172Type: `object`173174Same as [`fetch` options](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options), plus the following additional options:175176##### method177178Type: `string`\179Default: `'get'`180181HTTP method used to make the request.182Add QUERY method support (#873)Sindre Sorhusbefore adoption6edddd9
line 183why, one step back183Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD`, `DELETE`, and `QUERY`) are uppercased in order to avoid server errors due to case sensitivity.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 184–188why, one step back184185##### json186187Type: `object` and any other value accepted by [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)188Fix typos (#852)Rohit Nair Pbefore adoption6d12e2d
line 189why, one step back189Shortcut for sending JSON. Use this instead of the `body` option. Accepts any plain object or value, which will be stringified using `JSON.stringify()` and sent in the body with the correct header set.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 190why, one step back190Fix `json` option keeping the content-type inherited from a `Request` input bodySindre Sorhusbefore adoption0f2de47
lines 191–192why, one step back191The `Content-Type` header is set to `application/json` unless you set a `Content-Type` in the `headers` option, which always takes precedence. A `Content-Type` on a `Request` input is replaced, because the `Request` constructor sets one automatically from its body.192Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 193–197why, one step back193##### searchParams194195Type: `string | object<string, string | number | boolean | undefined> | Array<Array<string | number | boolean>> | URLSearchParams`\196Default: `''`197Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe
line 198why, one step back198Search parameters to include in the request URL. Setting this will merge with any existing search parameters in the input URL.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 199–201why, one step back199200Accepts any value supported by [`URLSearchParams()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams).201Fix a search parameter removed with `undefined` staying in the input URL when a later layer re-adds itSindre Sorhusbefore adoption91ea8a9
line 202why, one step back202When passing an object, setting a value to `undefined` deletes the parameter, including from the input URL, even when a later option layer adds the parameter again. `null` values are preserved and converted to the string `'null'`.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 203why, one step back203Improve docsSindre Sorhusbefore adoption8778439
line 204why, one step back204When `input` is a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) with a body, the body is sent as a stream, which requires [request stream support](https://caniuse.com/wf-fetch-request-streams) and, in Chromium-based browsers, an HTTP/2 or HTTP/3 connection (streaming uploads over HTTP/1.1 fail with a network error, even over plain HTTP). The inherited body is dropped when the search parameters change the URL and the request has to be rebuilt in an environment that cannot reuse it, which is the case without request stream support, when `keepalive` is true, or when the effective mode is `'no-cors'`. A search parameter value that leaves the URL unchanged does not rebuild the request, so the body is kept. A compatible body passed explicitly with the `body` option is still used.Fix `Request` input body being dropped when using `searchParams`Sindre Sorhusbefore adoptionb4bdecc
line 205why, one step back205Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
line 206why, one step back206##### baseUrlAdd retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 207–209why, one step back207208Type: `string | URL`209Fix typosSindre Sorhusbefore adoptionbbc98fc
line 210why, one step back210A base URL to [resolve](https://developer.mozilla.org/en-US/docs/Web/API/URL_API/Resolving_relative_references) the `input` against. When the `input` (after applying the `prefix` option) is only a relative URL, such as `'users'`, `'/users'`, or `'//my-site.com'`, it will be resolved against the `baseUrl` to determine the destination of the request. Otherwise, the `input` is absolute, such as `'https://my-site.com'`, and it will bypass the `baseUrl`.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 211why, one step back211Fix minor typos and improve backtick consistency (#853)Rohit Nair Pbefore adoptiona376fc4
line 212why, one step back212Useful when used with [`ky.extend()`](#kyextenddefaultoptions) to create niche-specific Ky instances.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 213why, one step back213Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
lines 214–217why, one step back214If the `baseUrl` itself is relative, it will be resolved against the environment's base URL, such as [`document.baseURI`](https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI) in browsers or `location.href` in Deno (see the `--location` flag).215216**Tip:** When setting a `baseUrl` that has a path, we recommend that it include a trailing slash `/`, as in `'/api/'` rather than `/api`. This ensures more intuitive behavior for page-relative `input` URLs, such as `'users'` or `'./users'`, where they will _extend_ from the full path of the `baseUrl` rather than _replacing_ its last path segment.217Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 218–222why, one step back218```js219import ky from 'ky';220221// On https://example.com222Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
lines 223–224why, one step back223const response = await ky('users', {baseUrl: '/api/'});224//=> 'https://example.com/api/users'Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 225why, one step back225Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
lines 226–227why, one step back226const response = await ky('/users', {baseUrl: '/api/'});227//=> 'https://example.com/users'Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 228–229why, one step back228```229Readme tweaksSindre Sorhusbefore adoption7f2eade
lines 230–231why, one step back230See [FAQ: `baseUrl` vs `prefix`](#baseurl-vs-prefix)231Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
lines 232–237why, one step back232##### prefix233234Type: `string | URL`235236A prefix to prepend to the `input` before making the request (and before it is resolved against the `baseUrl`). It can be any valid path or 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.237Fix minor typos and improve backtick consistency (#853)Rohit Nair Pbefore adoptiona376fc4
line 238why, one step back238Useful when used with [`ky.extend()`](#kyextenddefaultoptions) to create niche-specific Ky instances.Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
lines 239–241why, one step back239240*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.*241Readme tweaksSindre Sorhusbefore adoption7f2eade
lines 242–243why, one step back242See [FAQ: `baseUrl` vs `prefix`](#baseurl-vs-prefix)243Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
lines 244–255why, one step back244```js245import ky from 'ky';246247// On https://example.com248249const response = await ky('users', {prefix: '/api/'});250//=> 'https://example.com/api/users'251252const response = await ky('/users', {prefix: '/api/'});253//=> 'https://example.com/api/users'254```255Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 256why, one step back256Notes:Minor tweaksSindre Sorhusbefore adoption4b37c96
line 257why, one step back257 - The `prefix` and `input` are joined with a slash `/`, and slashes are normalized at the join boundary by trimming trailing slashes from `prefix` and leading slashes from `input`.Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
line 258why, one step back258 - After `prefix` and `input` are joined, the result is resolved against the `baseUrl` option, if present.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 259–264why, one step back259260##### retry261262Type: `object | number`\263Default:264- `limit`: `2`Add QUERY method support (#873)Sindre Sorhusbefore adoption6edddd9
line 265why, one step back265- `methods`: `get` `put` `head` `delete` `options` `trace` `query`Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 266–267why, one step back266- `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)267- `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)Readme tweaksSindre Sorhusbefore adoption7f2eade
lines 268–269why, one step back268- `maxRetryAfter`: `Infinity`269- `backoffLimit`: `Infinity`Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 270why, one step back270- `delay`: `attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000`Add `retry.jitter` option (#760)Sindre Sorhusbefore adoption081c924
line 271why, one step back271- `jitter`: `undefined`Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
lines 272–273why, one step back272- `retryOnTimeout`: `false`273- `shouldRetry`: `undefined`Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 274why, one step back274Readme tweaksSindre Sorhusbefore adoption7f2eade
line 275why, one step back275Controls retry behavior. Each field is documented individually below.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 276–278why, one step back276277If `retry` is a number, it will be used as `limit` and other defaults will remain in place.278Harden retrySindre Sorhusbefore adoptionc426f19
lines 279–280why, one step back279`retry.limit`, including numeric shorthand, must be a finite, non-negative integer.280Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
lines 281–282why, one step back281Network 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.282Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8
lines 283–284why, one step back283A hook can change `retry.limit` through `options`. Ky reads the limit again when each attempt starts. A `beforeRequest` or `beforeRetry` hook runs before the attempt starts, so it can lower or raise the limit. An `afterResponse` hook runs after the attempt started, so it can lower the limit, for example to stop retrying once a response says so. A higher limit set there only applies from the next attempt.284Improve docsSindre Sorhusbefore adoption8778439
line 285why, one step back285`413 Payload Too Large` is only retried when the response includes a retry timing header, unless `shouldRetry` returns `true`.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 286why, one step back286Skip wrapping a body a hook read, and read a past reset epoch as a timestampSindre Sorhusbefore adoption23ca564
line 287why, one step back287When the response status is contained in `afterStatusCodes` and the retry is allowed by `statusCodes` or `shouldRetry`, Ky uses retry timing headers to choose the retry delay. [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) may provide a delay in seconds or an HTTP-date. If `Retry-After` is missing, Ky falls back to rate-limit timing headers (`RateLimit-Reset`, `X-RateLimit-Retry-After`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset`). Numeric `Retry-After` and `X-RateLimit-Retry-After` values are interpreted as delay seconds. Numeric `RateLimit-Reset`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset` values may also be interpreted as Unix timestamps, from 2001-09-09 onwards. A value below that is read as delay seconds, and a timestamp already in the past means the retry happens immediately. If the status code is not in `afterStatusCodes`, retry timing headers will be ignored.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 288why, one step back288Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 289–290why, one step back289If the retry delay from a retry timing header is greater than `maxRetryAfter`, Ky will use `maxRetryAfter`.290Improve docsSindre Sorhusbefore adoption8778439
line 291why, one step back291The `backoffLimit` option is the upper limit of the delay per retry in milliseconds, for the delay calculated by `retry.delay`.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 292why, one step back292To clamp the delay, set `backoffLimit` to 1000, for example.Improve docsSindre Sorhusbefore adoption8778439
line 293why, one step back293A delay from a retry timing header is not subject to this limit; use `maxRetryAfter` to bound it.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 294–295why, one step back294By default, the delay is calculated with `0.3 * (2 ** (attemptCount - 1)) * 1000`. The delay increases exponentially.295Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8
line 296why, one step back296The `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. A value that is not a non-negative number or `Infinity` throws a `TypeError` rather than collapsing to a 1ms retry, and the error that was being retried is kept as its `cause` so `beforeError` can still reach it.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 297why, one step back297Add `retry.jitter` option (#760)Sindre Sorhusbefore adoption081c924
lines 298–299why, one step back298The `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.299Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
line 300why, one step back300**Note:** Jitter is not applied when the server provides a retry timing header, as the server's explicit timing should be respected.Add `retry.jitter` option (#760)Sindre Sorhusbefore adoption081c924
line 301why, one step back301Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
line 302why, one step back302The `retryOnTimeout` option determines whether to retry when a request times out before a response is returned. By default, retries are not triggered following a [timeout](#timeout). Timeouts while reading a response body through Ky shortcut methods are not retried because the response has already been received.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 303why, one step back303Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 304why, one step back304The `shouldRetry` option provides custom retry logic that **takes precedence over the default retry checks** (`retryOnTimeout`, status code checks, etc.) for retriable methods. It is only called after the retry limit and method checks pass.Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
lines 305–310why, one step back305306**Note:** This is different from the `beforeRetry` hook:307- `shouldRetry`: Controls WHETHER to retry (called before the retry decision is made)308- `beforeRetry`: Called AFTER retry is confirmed, allowing you to modify the request309310The function receives a state object with the error and retry count (starts at 1 for the first retry), and should return:Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 311why, one step back311- `true` to force a retry (bypasses `retryOnTimeout`, status code checks, and other default validations)Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
line 312why, one step back312- `false` to prevent a retry (no retry will occur)Fix `shouldRetry` type rejecting functions that return nothingSindre Sorhusbefore adoption178767e
line 313why, one step back313- `undefined` (or nothing) to use the default retry logic (`retryOnTimeout`, status codes, network errors). Unrecognized error types are not retried.Honour a server retry-timing header when `shouldRetry` allows the retrySindre Sorhusbefore adoptiond1c921f
lines 314–315why, one step back314315Returning `true` overrides retry eligibility, not timing. For HTTP errors with a status in `afterStatusCodes`, retry timing headers and `maxRetryAfter` still apply, without jitter. Otherwise, Ky uses the configured backoff delay.Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
lines 316–318why, one step back316317**General example**318Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 319–325why, one step back319```js320import ky from 'ky';321322const json = await ky('https://example.com', {323 retry: {324 limit: 10,325 methods: ['get'],Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
line 326why, one step back326 statusCodes: [500],Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 327why, one step back327 backoffLimit: 3000Add `retry.jitter` option (#760)Sindre Sorhusbefore adoption081c924
lines 328–331why, one step back328 }329}).json();330```331Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
lines 332–333why, one step back332**Retrying on timeout:**333Add `retry.jitter` option (#760)Sindre Sorhusbefore adoption081c924
lines 334–337why, one step back334```js335import ky from 'ky';336337const json = await ky('https://example.com', {Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
line 338why, one step back338 timeout: 5000,Add `retry.jitter` option (#760)Sindre Sorhusbefore adoption081c924
line 339why, one step back339 retry: {Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
lines 340–352why, one step back340 limit: 3,341 retryOnTimeout: true342 }343}).json();344```345346**Using jitter to prevent thundering herd:**347348```js349import ky from 'ky';350351const json = await ky('https://example.com', {352 retry: {Add `retry.jitter` option (#760)Sindre Sorhusbefore adoption081c924
lines 353–362why, one step back353 limit: 5,354355 // Full jitter (randomizes delay between 0 and computed value)356 jitter: true357358 // Percentage jitter (80-120% of delay)359 // jitter: delay => delay * (0.8 + Math.random() * 0.4)360361 // Absolute jitter (±100ms)362 // jitter: delay => delay + (Math.random() * 200 - 100)Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4
lines 363–393why, one step back363 }364}).json();365```366367**Custom retry logic:**368369```js370import ky, {HTTPError} from 'ky';371372const json = await ky('https://example.com', {373 retry: {374 limit: 3,375 shouldRetry: ({error, retryCount}) => {376 // Retry on specific business logic errors from API377 if (error instanceof HTTPError) {378 const status = error.response.status;379380 // Retry on 429 (rate limit) but only for first 2 attempts381 if (status === 429 && retryCount <= 2) {382 return true;383 }384385 // Don't retry on 4xx errors except rate limits386 if (status >= 400 && status < 500) {387 return false;388 }389 }390391 // Use default retry logic for other errors392 return undefined;393 }Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 394–397why, one step back394 }395}).json();396```397Document Chromium's automatic retry behavior for 408 status codesSindre Sorhusbefore adoptionec10a68
line 398why, one step back398> [!NOTE]Document streaming request body behavior and retry memory implicationsSindre Sorhusbefore adoptionc168a7c
lines 399–401why, one step back399> When retries are enabled, Ky clones the request body before each attempt using [`tee()`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/tee), which buffers the entire `ReadableStream` in memory. Set `retry: {limit: 0}` if you're uploading large streaming bodies and don't need retries.400401> [!NOTE]Document Chromium's automatic retry behavior for 408 status codesSindre Sorhusbefore adoptionec10a68
lines 402–403why, one step back402> Chromium-based browsers automatically retry `408 Request Timeout` responses at the network layer for keep-alive connections. This means requests may be retried by both the browser and ky. If you want to avoid duplicate retries, you can either set `keepalive: false` in your request options (though this may impact performance for multiple requests) or remove `408` from the retry status codes.403Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 404–408why, one step back404##### timeout405406Type: `number | false`\407Default: `10000`408TweaksSindre Sorhusbefore adoption3ded2aa
line 409why, one step back409Per-attempt timeout in milliseconds for getting a response, applied independently to each retry. Ky shortcut methods also use this value as a separate timeout for reading the response body. Must be a non-negative number or `false`, or a `TypeError` is thrown. A value greater than 2147483647, `Infinity` included, throws a `RangeError`. See also [`totalTimeout`](#totaltimeout).Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7
lines 410–412why, one step back410411If set to `false`, there will be no per-attempt timeout.412Explain both causes of a missing response and document the new validationSindre Sorhusbefore adoption58233f1
lines 413–414why, one step back413If the signal you passed in is aborted while a body method is reading, or just after the read finished, the body method rejects with the abort reason rather than resolving with the bytes that already arrived.414Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7
lines 415–419why, one step back415##### totalTimeout416417Type: `number | false`\418Default: `false`419TweaksSindre Sorhusbefore adoption3ded2aa
line 420why, one step back420Overall timeout in milliseconds for the entire operation, including retries and delays. Throws a `TimeoutError` if exceeded. Must be a non-negative number or `false`, or a `TypeError` is thrown. A value greater than 2147483647, `Infinity` included, throws a `RangeError`.Harden retrySindre Sorhusbefore adoptionc426f19
lines 421–422why, one step back421422`beforeError` hooks run after an error is produced and are not bounded by `totalTimeout`.Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7
lines 423–438why, one step back423424If set to `false` or not specified, there is no overall timeout.425426```js427import ky from 'ky';428429// Each attempt gets 5s, but the whole operation must complete within 30s430const json = await ky('https://example.com', {431 timeout: 5000,432 totalTimeout: 30_000,433 retry: {434 limit: 3,435 retryOnTimeout: true,436 }437}).json();438```Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 439why, one step back439Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
lines 440–450why, one step back440##### maxResponseSize441442Type: `number`\443Default: `Infinity`444445Maximum response body size in bytes. Must be a non-negative safe integer or `Infinity`. Set to `0` to allow only empty bodies.446447The limit counts bytes from the response stream after decompression, independently of `Content-Length`. It applies as the body is consumed, including in `afterResponse` hooks and for responses returned by hooks. Exceeding the limit cancels the stream and throws a `ResponseSizeError`, without automatically retrying.448449With `await ky(url)`, the response can resolve before the limit is exceeded; the body read will reject instead. This limits body bytes, not total memory usage. Parsing, buffering, and concurrent requests can use additional memory.450Improve docsSindre Sorhusbefore adoption8778439
lines 451–452why, one step back451Responses with a [null body status](https://fetch.spec.whatwg.org/#null-body-status), such as `204` and `205`, are never wrapped, because the `Response` constructor rejects a body for those statuses. A runtime that still exposes a body for such a status, such as WebKit for `205`, is therefore not limited.452Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
lines 453–460why, one step back453```js454import ky from 'ky';455456const data = await ky('https://example.com/data', {457 maxResponseSize: 20 * 1024 * 1024,458}).json();459```460Explain both causes of a missing response and document the new validationSindre Sorhusbefore adoption58233f1
lines 461–470why, one step back461##### dispatcher462463An [undici](https://github.com/nodejs/undici) `Agent` or `Dispatcher`, forwarded to `fetch()` as-is. Ky does not use it, it just passes it through.464465##### next466467A framework-specific fetch extension, such as [Next.js's `next`](https://nextjs.org/docs/app/api-reference/functions/next#options), forwarded to `fetch()` as-is.468469Ky forwards every option it does not recognize to `fetch()`. The type of such an option comes from the global `RequestInit` type, which `@types/node` extends with `dispatcher` and Next.js extends with `next`. An extension that your environment does not declare needs a type assertion.470Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 471–473why, one step back471##### hooks472473Type: `object<string, Function[]>`\Add `init` hook (#841)Sindre Sorhusbefore adoption87c6740
line 474why, one step back474Default: `{init: [], beforeRequest: [], beforeRetry: [], beforeError: [], afterResponse: []}`Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 475why, one step back475Add `init` hook (#841)Sindre Sorhusbefore adoption87c6740
lines 476–477why, one step back476Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially, unless otherwise noted.477Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8
line 478why, one step back478Each hook must be an array of functions. A single function, a string, or any other value, `null` included, throws a `TypeError` rather than being silently dropped. `undefined` means absent, so it clears the hooks it would have replaced.Explain both causes of a missing response and document the new validationSindre Sorhusbefore adoption58233f1
line 479why, one step back479Add `init` hook (#841)Sindre Sorhusbefore adoption87c6740
lines 480–484why, one step back480###### hooks.init481482Type: `Function[]`\483Default: `[]`484TweaksSindre Sorhusbefore adoption3ded2aa
line 485why, one step back485This hook enables you to modify the options before they are used to construct the request. The hook function receives the mutable options object and can modify it in place. You could, for example, modify `searchParams`, `headers`, or `json` here. The `headers` option starts as a plain object with lowercase names, where a header removed with `undefined` keeps an `undefined` value.Add `init` hook (#841)Sindre Sorhusbefore adoption87c6740
line 486why, one step back486Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5
line 487why, one step back487Ky gives the hook its own copies of `headers`, `context`, `json`, `searchParams` and `retry`, so changing them in place only affects the current request. The `context` copy is shallow, the same as in every other hook, so nested `context` values, such as a cache, stay shared across requests. The `body` option is not copied, so mutating a `FormData` or `URLSearchParams` body in place changes your own object and repeats on every request from the same instance. Assign a new instance instead, as shown in [Modifying FormData in hooks](#modifying-formdata-in-hooks). A value that a hook assigns is used as is, so assign a new object rather than one that you change later.Add `init` hook (#841)Sindre Sorhusbefore adoption87c6740
line 488why, one step back488TweaksSindre Sorhusbefore adoption3ded2aa
line 489why, one step back489Unlike other hooks, `init` hooks are synchronous. An error thrown by one rejects the returned promise and is not passed to `beforeError` hooks.HardenSindre Sorhusbefore adoption8d8e7a4
line 490why, one step back490Add `init` hook (#841)Sindre Sorhusbefore adoption87c6740
lines 491–508why, one step back491A common use case is to add a search parameter to every request:492493```js494import ky from 'ky';495496const api = ky.extend({497 hooks: {498 init: [499 options => {500 options.searchParams = {apiKey: getApiKey()};501 },502 ],503 },504});505506const response = await api.get('https://example.com/api/users');507// URL: https://example.com/api/users?apiKey=123508```Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 509–514why, one step back509510###### hooks.beforeRequest511512Type: `Function[]`\513Default: `[]`514TweaksSindre Sorhusbefore adoption191057d
line 515why, one step back515This 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 a state object with the normalized request, options, and retry count. You could, for example, modify `request.headers` here.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 516why, one step back516Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 517why, one step back517The `retryCount` is always `0`, since `beforeRequest` hooks run once before retry handling begins.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 518why, one step back518Fix timeouts and user aborts not cancelling a `Request` returned from `beforeRequest` or `beforeRetry` hooksSindre Sorhusbefore adoptione1b088e
line 519why, one step back519The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing request (remaining hooks will still run with the updated request). It can also return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to completely avoid making an HTTP request, in which case remaining `beforeRequest` hooks are skipped. This can be used to mock a request, check an internal cache, etc. A returned `Request` instance's `signal` is replaced with Ky's managed signal so that timeouts and user-provided abort signals still work.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 520why, one step back520Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 521–522why, one step back521Any error thrown by `beforeRequest` hooks is treated as fatal and will not trigger Ky's retry logic.522Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 523–528why, one step back523```js524import ky from 'ky';525526const api = ky.extend({527 hooks: {528 beforeRequest: [Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
lines 529–530why, one step back529 ({request}) => {530 request.headers.set('Authorization', 'token initial-token');Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 531–538why, one step back531 }532 ]533 }534});535536const response = await api.get('https://example.com/api/users');537```538Document and test URL modification in `beforeRequest` hookSindre Sorhusbefore adoption648e25d
lines 539–558why, one step back539**Modifying the request URL:**540541```js542import ky from 'ky';543544const api = ky.extend({545 hooks: {546 beforeRequest: [547 ({request}) => {548 const url = new URL(request.url);549 url.searchParams.set('token', 'secret-token');550 return new Request(url, request);551 }552 ]553 }554});555556const response = await api.get('https://example.com/api/users');557```558Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 559–563why, one step back559###### hooks.beforeRetry560561Type: `Function[]`\562Default: `[]`563TweaksSindre Sorhusbefore adoption191057d
line 564why, one step back564This 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 a state object with the normalized request, options, an error instance, and retry count. You could, for example, modify `request.headers` here.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 565why, one step back565Fix timeouts and user aborts not cancelling a `Request` returned from `beforeRequest` or `beforeRetry` hooksSindre Sorhusbefore adoptione1b088e
line 566why, one step back566The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing retry request, or return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to skip the retry and use that response instead. A returned `Request` instance's `signal` is replaced with Ky's managed signal so that timeouts and user-provided abort signals still work. **Note:** Returning a request or response skips remaining `beforeRetry` hooks.Allow `beforeRetry` hooks to return a `Request` or `Response` (#774)Sindre Sorhusbefore adoptiona51bb1e
line 567why, one step back567TweaksSindre Sorhusbefore adoption8f28eac
lines 568–570why, one step back568> [!WARNING]569> Returned `Request` objects are used as-is. If you point one at another origin, remove any credentials you do not want forwarded.570TweaksSindre Sorhusbefore adoption191057d
line 571why, one step back571The `retryCount` is always `>= 1`, since this hook is only called during retries, not on the initial request.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 572why, one step back572Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
line 573why, one step back573If the request received a response, the error will be of type `HTTPError`. The `Response` object will be available at `error.response`, and the pre-parsed response body may be available at `error.data`. 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`.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 574–576why, one step back574575You 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).576Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327
lines 577–601why, one step back577**Changing options:**578579Return `{options: {...}}` to change `onUploadProgress`, `onDownloadProgress`, `timeout`, `fetch`, or `throwHttpErrors` for this retry and the ones after it. Omitted options keep their value, and `undefined` restores Ky's default, not the value from `ky.create()` or `ky.extend()`. Any other option, or an invalid value, throws an error. The remaining `beforeRetry` hooks still run and see the new progress callbacks in `options`. The `options` a hook receives never include `timeout`, `fetch`, or `throwHttpErrors`.580581For example, turn off upload progress after a network error. Upload progress needs a streamed request body, which Chromium only sends over HTTP/2 or HTTP/3, so the upload fails on an HTTP/1.1 connection. Only retry an upload when it is safe to send it again, since a network error does not tell whether the server got the request.582583```js584import ky, {isNetworkError} from 'ky';585586await ky.put(uploadUrl, {587 body: file,588 onUploadProgress: updateProgress,589 retry: {limit: 1},590 hooks: {591 beforeRetry: [592 ({error}) => {593 if (isNetworkError(error)) {594 return {options: {onUploadProgress: undefined}};595 }596 }597 ]598 }599});600```601Allow `beforeRetry` hooks to return a `Request` or `Response` (#774)Sindre Sorhusbefore adoptiona51bb1e
lines 602–603why, one step back602**Modifying headers:**603Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 604–612why, one step back604```js605import ky from 'ky';606607const response = await ky('https://example.com', {608 hooks: {609 beforeRetry: [610 async ({request, options, error, retryCount}) => {611 const token = await ky('https://example.com/refresh-token');612 request.headers.set('Authorization', `token ${token}`);Allow `beforeRetry` hooks to return a `Request` or `Response` (#774)Sindre Sorhusbefore adoptiona51bb1e
lines 613–621why, one step back613 }614 ]615 }616});617```618619**Modifying the request URL:**620621```jsAdd `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
line 622why, one step back622import ky, {isHTTPError} from 'ky';Allow `beforeRetry` hooks to return a `Request` or `Response` (#774)Sindre Sorhusbefore adoptiona51bb1e
lines 623–626why, one step back623624const response = await ky('https://example.com/api', {625 hooks: {626 beforeRetry: [Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
line 627why, one step back627 ({request, error}) => {Allow `beforeRetry` hooks to return a `Request` or `Response` (#774)Sindre Sorhusbefore adoptiona51bb1e
line 628why, one step back628 // Add query parameters based on error responseAdd `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
lines 629–634why, one step back629 if (630 isHTTPError(error)631 && typeof error.data === 'object'632 && error.data !== null633 && 'processId' in error.data634 ) {Allow `beforeRetry` hooks to return a `Request` or `Response` (#774)Sindre Sorhusbefore adoptiona51bb1e
line 635why, one step back635 const url = new URL(request.url);Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
line 636why, one step back636 url.searchParams.set('processId', String(error.data.processId));Allow `beforeRetry` hooks to return a `Request` or `Response` (#774)Sindre Sorhusbefore adoptiona51bb1e
lines 637–657why, one step back637 return new Request(url, request);638 }639 }640 ]641 }642});643```644645**Returning a cached response:**646647```js648import ky from 'ky';649650const response = await ky('https://example.com/api', {651 hooks: {652 beforeRetry: [653 ({error, retryCount}) => {654 // Use cached response instead of retrying655 if (retryCount > 1 && cachedResponse) {656 return cachedResponse;657 }Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 658–668why, one step back658 }659 ]660 }661});662```663664###### hooks.beforeError665666Type: `Function[]`\667Default: `[]`668Fix typosSindre Sorhusbefore adoptionbbc98fc
line 669why, one step back669This hook enables you to modify any error right before it is thrown. The hook function receives a state object with the current request, the normalized Ky options, the error, and retry count, and should return an `Error` instance.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 670why, one step back670Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
line 671why, one step back671This hook receives errors Ky handles during its request lifecycle, including `HTTPError`, `NetworkError`, `TimeoutError`, `ResponseSizeError`, and `ForceRetryError` (when retry limit is exceeded via `ky.retry()`). Use type guards like `isHTTPError()`, `isNetworkError()`, `isTimeoutError()`, or `isResponseSizeError()` to handle specific error types.Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
line 672why, one step back672Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
lines 673–674why, one step back673Errors raised while consuming an already returned `Response` are outside the request lifecycle. Use a body method shortcut like `await ky(url).json()` to process body-read `ResponseSizeError`, `NetworkError`, and `TimeoutError` instances through this hook.674Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e
line 675why, one step back675The `retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between the initial request and retries, which is useful when you need different error handling based on retry attempts (e.g., showing different error messages on the final attempt).Various tweaksSindre Sorhusbefore adoption0dd9522
lines 676–677why, one step back676677If a `beforeRequest` or `beforeRetry` hook returns a new `Request`, inspect `request` for the final request state. `options` remains Ky's normalized options and may not mirror every property of a replacement `Request`.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 678–679why, one step back678679```jsAdd `request` and `options` to `beforeError` hook state (#835)Sindre Sorhusbefore adoption01e0b85
line 680why, one step back680import ky, {isHTTPError} from 'ky';Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 681–684why, one step back681682await ky('https://example.com', {683 hooks: {684 beforeError: [Add `request` and `options` to `beforeError` hook state (#835)Sindre Sorhusbefore adoption01e0b85
line 685why, one step back685 ({request, options, error}) => {Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
lines 686–694why, one step back686 if (isHTTPError(error)) {687 if (688 typeof error.data === 'object'689 && error.data !== null690 && 'message' in error.data691 ) {692 error.name = 'GitHubError';693 error.message = `${String(error.data.message)} (${error.response.status})`;694 }Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 695–696why, one step back695 }696Add `request` and `options` to `beforeError` hook state (#835)Sindre Sorhusbefore adoption01e0b85
lines 697–698why, one step back697 // `request` and `options` are always available698 console.log(`Request to ${request.url} failed`, options.context);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 699–711why, one step back699700 return error;701 }702 ]703 }704});705```706707###### hooks.afterResponse708709Type: `Function[]`\710Default: `[]`711Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e
line 712why, one step back712This hook enables you to read and optionally modify the response. The hook function receives a state object with the normalized request, options, a clone of the response, and retry count. 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).Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 713why, one step back713Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
line 714why, one step back714You can also force a retry by returning [`ky.retry(options)`](#kyretryoptions). This is useful when you need to retry based on the response body content, even if the response has a successful status code. The retry will respect the `retry.limit` option and be observable in `beforeRetry` hooks.Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 715why, one step back715TweaksSindre Sorhusbefore adoption8f28eac
lines 716–718why, one step back716> [!WARNING]717> `ky.retry({request})` uses the replacement request as-is. If it targets another origin, remove any credentials you do not want forwarded.718Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00
line 719why, one step back719Any non-`ky.retry()` error thrown by `afterResponse` hooks is treated as fatal and will not trigger Ky's retry logic.Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
line 720why, one step back720TweaksSindre Sorhusbefore adoption191057d
line 721why, one step back721The `retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between the initial request and retries, which is useful when you need different behavior for retries (e.g., showing a notification only on the final retry).Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 722–728why, one step back722723```js724import ky from 'ky';725726const response = await ky('https://example.com', {727 hooks: {728 afterResponse: [Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e
line 729why, one step back729 ({response}) => {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 730–736why, one step back730 // You could do something with the response, for example, logging.731 log(response);732733 // Or return a `Response` instance to overwrite the response.734 return new Response('A different response', {status: 200});735 },736Add 401 token refresh pattern tests and examplesSindre Sorhusbefore adoption337a1b2
line 737why, one step back737 // Or retry with a fresh token on a 401 errorUnify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e
lines 738–739why, one step back738 async ({request, response, retryCount}) => {739 if (response.status === 401 && retryCount === 0) {Add 401 token refresh pattern tests and examplesSindre Sorhusbefore adoption337a1b2
lines 740–741why, one step back740 // Only refresh on first 401, not on subsequent retries741 const {token} = await ky.post('https://example.com/auth/refresh').json();Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 742why, one step back742Add 401 token refresh pattern tests and examplesSindre Sorhusbefore adoption337a1b2
lines 743–744why, one step back743 const headers = new Headers(request.headers);744 headers.set('Authorization', `Bearer ${token}`);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 745why, one step back745Add 401 token refresh pattern tests and examplesSindre Sorhusbefore adoption337a1b2
lines 746–749why, one step back746 return ky.retry({747 request: new Request(request, {headers}),748 code: 'TOKEN_REFRESHED'749 });Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 750–752why, one step back750 }751 },752Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
line 753why, one step back753 // Or force retry based on response body contentUnify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e
line 754why, one step back754 async ({response}) => {Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
line 755why, one step back755 if (response.status === 200) {Readme tweaksSindre Sorhusbefore adoption7f2eade
line 756why, one step back756 const data = await response.json();Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
lines 757–766why, one step back757 if (data.error?.code === 'RATE_LIMIT') {758 // Retry with custom delay from API response759 return ky.retry({760 delay: data.error.retryAfter * 1000,761 code: 'RATE_LIMIT'762 });763 }764 }765 },766Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 767why, one step back767 // Or show a notification only on the last retry for 5xx errorsUnify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e
line 768why, one step back768 ({options, response, retryCount}) => {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 769–781why, one step back769 if (response.status >= 500 && response.status <= 599) {770 if (retryCount === options.retry.limit) {771 showNotification('Request failed after all retries');772 }773 }774 }775 ]776 }777});778```779780##### throwHttpErrors781Allow `throwHttpErrors` option to be a function (#781)Sindre Sorhusbefore adoption84ff3b9
line 782why, one step back782Type: `boolean | (status: number) => boolean`\Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 783–787why, one step back783Default: `true`784785Throw 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'`.786787Setting this to `false` may be useful if you are checking for resource availability and are expecting error responses.Allow `throwHttpErrors` option to be a function (#781)Sindre Sorhusbefore adoption84ff3b9
lines 788–789why, one step back788789You can also pass a function that accepts the HTTP status code and returns a boolean for selective error handling. Note that this can violate the principle of least surprise, so it's recommended to use the boolean form unless you have a specific use case like treating 404 responses differently.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 790–792why, one step back790791Note: If `false`, error responses are considered successful and the request will not be retried.792Don't throw `HTTPError` for opaque responses from `no-cors` requests (#847)Sindre Sorhusbefore adoption1d15eb6
lines 793–794why, one step back793Note: [Opaque responses](https://developer.mozilla.org/en-US/docs/Web/API/Response/type) from `no-cors` requests are returned as-is (without throwing `HTTPError`), since the actual status is hidden by the browser.794Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 795–801why, one step back795##### onDownloadProgress796797Type: `Function`798799Download progress event handler.800801The function receives these arguments:Gracefully ignore `onUploadProgress` when request streams are unsupported (#845)Sindre Sorhusbefore adoption1e38ff4
line 802why, one step back802- `progress` is an object with these properties:Readme tweaksSindre Sorhusbefore adoption7f2eade
lines 803–804why, one step back803 - `percent` is a number between 0 and 1 representing the progress percentage.804 - `transferredBytes` is the number of bytes transferred so far.Fix progress callbacks for empty request and response bodies (#881)Sindre Sorhusbefore adoption99644d0
lines 805–806why, one step back805 - `totalBytes` is the total number of bytes to be transferred. This is an estimate and may be 0 for an empty transfer or when the total size cannot be determined.806- `chunk` is an instance of `Uint8Array` containing the data that was received. When an empty response body stream completes, the callback receives an empty chunk.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 807why, one step back807Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d
line 808why, one step back808`content-length` is only used as the total for a response that is not content-coded, since it counts encoded bytes while the progress stream counts the bytes after decompression. A compressed response therefore reports `totalBytes: 0` until it completes, so the percentage cannot be calculated while downloading. For a cross-origin response in a browser, `content-encoding` is only visible when the server lists it in `Access-Control-Expose-Headers`. Otherwise Ky cannot tell that the response is compressed, so it uses `content-length` and the percentage stays close to 100% for most of the download.Count a compressed response as unknown, deep-copy context, and isolate `init` hook assignmentsSindre Sorhusbefore adoptiond89c8c8
line 809why, one step back809Explain both causes of a missing response and document the new validationSindre Sorhusbefore adoption58233f1
line 810why, one step back810Responses with no body at all are not streamed, so no progress events are emitted for them. That covers a [null body status](https://fetch.spec.whatwg.org/#null-body-status) such as `204`, and a `HEAD` response in runtimes that give it no body, such as browsers, Node.js and Deno. Bun gives a `HEAD` response an empty body, so it reports one final event with `transferredBytes: 0`. A response whose body an `afterResponse` hook already read, or locked with a reader, is passed through unchanged, so it reports no progress either.Improve docsSindre Sorhusbefore adoption8778439
line 811why, one step back811Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5
line 812why, one step back812Do not throw from the callback. A throw fails the response stream, which the runtime reports in its own way: Node.js rejects the body read with your error, while Chromium reports a network failure, so Ky's body methods throw a `NetworkError` there. Pass a `signal` from an `AbortController` to cancel instead.Improve docsSindre Sorhusbefore adoption8778439
line 813why, one step back813Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 814–831why, one step back814```js815import ky from 'ky';816817const response = await ky('https://example.com', {818 onDownloadProgress: (progress, chunk) => {819 // Example output:820 // `100% - 1271 of 1271 bytes`821 console.log(`${progress.percent * 100}% - ${progress.transferredBytes} of ${progress.totalBytes} bytes`);822 }823});824```825826##### onUploadProgress827828Type: `Function`829830Upload progress event handler.831Gracefully ignore `onUploadProgress` when request streams are unsupported (#845)Sindre Sorhusbefore adoption1e38ff4
line 832why, one step back832> [!NOTE]Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327
line 833why, one step back833> Requires [request stream support](https://caniuse.com/wf-fetch-request-streams) and, in Chromium-based browsers, an HTTP/2 or HTTP/3 connection (streaming uploads over HTTP/1.1 fail with a network error, even over plain HTTP). This handler is silently ignored in unsupported environments and for requests with `keepalive: true` or `mode: 'no-cors'`, since they cannot use streaming request bodies. If an upload fails over HTTP/1.1 in Chromium, you can retry it without upload progress by returning `{options: {onUploadProgress: undefined}}` from a [`beforeRetry`](#hooksbeforeretry) hook.Gracefully ignore `onUploadProgress` when request streams are unsupported (#845)Sindre Sorhusbefore adoption1e38ff4
line 834why, one step back834Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 835why, one step back835The function receives these arguments:Gracefully ignore `onUploadProgress` when request streams are unsupported (#845)Sindre Sorhusbefore adoption1e38ff4
line 836why, one step back836- `progress` is an object with these properties:Readme tweaksSindre Sorhusbefore adoption7f2eade
lines 837–838why, one step back837 - `percent` is a number between 0 and 1 representing the progress percentage.838 - `transferredBytes` is the number of bytes transferred so far.Fix progress callbacks for empty request and response bodies (#881)Sindre Sorhusbefore adoption99644d0
lines 839–840why, one step back839 - `totalBytes` is the total number of bytes to be transferred. This is an estimate and may be 0 for an empty transfer or when the total size cannot be determined.840- `chunk` is an instance of `Uint8Array` containing the data that was sent. When an empty request body stream completes, the callback receives an empty chunk.Progress from a declared content-length, and a throwing callback is never retriedSindre Sorhusbefore adoption0b1f462
line 841why, one step back841Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5
lines 842–844why, one step back842A `ReadableStream` body cannot be measured, so `totalBytes` falls back to a `content-length` header you set. Browsers do not allow that header on a request, so there the total stays `0`. When a hook replaces the request, `totalBytes` is still estimated from the `body` option until the final event, which reports the real total.843844Do not throw from the callback. A throw fails the upload stream, which the runtime reports as a network failure, so Ky throws a `NetworkError` (in Node.js, with your error in its `cause` chain) and retries it like any other network error, running the callback again. Pass a `signal` from an `AbortController` to cancel instead.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 845–865why, one step back845846```js847import ky from 'ky';848849const response = await ky.post('https://example.com/upload', {850 body: largeFile,851 onUploadProgress: (progress, chunk) => {852 // Example output:853 // `100% - 1271 of 1271 bytes`854 console.log(`${progress.percent * 100}% - ${progress.transferredBytes} of ${progress.totalBytes} bytes`);855 }856});857```858859##### parseJson860861Type: `Function`\862Default: `JSON.parse()`863864User-defined JSON-parsing function.865Add request/response context to `parseJson` option (#849)Sindre Sorhusbefore adoption3713ce8
lines 866–867why, one step back866The function receives the response text as the first argument and a context object as the second argument containing the `request` ([`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)) and `response` ([`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)).867Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 868–870why, one step back868Use-cases:8691. Parse JSON via the [`bourne` package](https://github.com/hapijs/bourne) to protect from prototype pollution.8702. Parse JSON with [`reviver` option of `JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).Add request/response context to `parseJson` option (#849)Sindre Sorhusbefore adoption3713ce8
line 871why, one step back8713. Log or handle JSON parse errors with request context.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 872–878why, one step back872873```js874import ky from 'ky';875import bourne from '@hapijs/bourne';876877const json = await ky('https://example.com', {878 parseJson: text => bourne(text)Add request/response context to `parseJson` option (#849)Sindre Sorhusbefore adoption3713ce8
lines 879–889why, one step back879}).json();880```881882```js883import ky from 'ky';884885const json = await ky('https://example.com', {886 parseJson: (text, {request, response}) => {887 console.log(`Parsing JSON from ${request.url} (status: ${response.status})`);888 return JSON.parse(text);889 }Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 890–923why, one step back890}).json();891```892893##### stringifyJson894895Type: `Function`\896Default: `JSON.stringify()`897898User-defined JSON-stringifying function.899900Use-cases:9011. Stringify JSON with a custom `replacer` function.902903```js904import ky from 'ky';905import {DateTime} from 'luxon';906907const json = await ky('https://example.com', {908 stringifyJson: data => JSON.stringify(data, (key, value) => {909 if (key.endsWith('_at')) {910 return DateTime.fromISO(value).toSeconds();911 }912913 return value;914 })915}).json();916```917918##### fetch919920Type: `Function`\921Default: `fetch`922923User-defined `fetch` function.TweaksSindre Sorhusbefore adoption3ded2aa
line 924why, one step back924Has to be fully compatible with the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) standard. It must resolve with a `Response`, or a `TypeError` is thrown.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 925–926why, one step back925926Use-cases:TweaksSindre Sorhusbefore adoption191057d
lines 927–928why, one step back9271. Use the `fetch` wrapper function provided by some frameworks that use server-side rendering (SSR).9282. Add custom instrumentation or logging to all requests.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 929–932why, one step back929930```js931import ky from 'ky';932TweaksSindre Sorhusbefore adoption191057d
lines 933–943why, one step back933const api = ky.create({934 fetch: async (request, init) => {935 const start = performance.now();936 const response = await fetch(request, init);937 const duration = performance.now() - start;938 console.log(`${request.method} ${request.url} - ${response.status} (${Math.round(duration)}ms)`);939 return response;940 }941});942943const json = await api('https://example.com').json();Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 944–945why, one step back944```945Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba
lines 946–969why, one step back946##### context947948Type: `object<string, unknown>`\949Default: `{}`950951User-defined data passed to hooks.952953This option allows you to pass arbitrary contextual data to hooks without polluting the request itself. The context is available in all hooks and is **guaranteed to always be an object** (never `undefined`), so you can safely access properties without optional chaining.954955Use cases:956- Pass authentication tokens or API keys to hooks957- Attach request metadata for logging or debugging958- Implement conditional logic in hooks based on the request context959- Pass serverless environment bindings (e.g., Cloudflare Workers)960961**Note:** Context is shallow merged. Top-level properties are merged, but nested objects are replaced. Only enumerable properties are copied.962963```js964import ky from 'ky';965966// Pass data to hooks967const api = ky.create({968 hooks: {969 beforeRequest: [Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e
line 970why, one step back970 ({request, options}) => {Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba
lines 971–1007why, one step back971 const {token} = options.context;972 if (token) {973 request.headers.set('Authorization', `Bearer ${token}`);974 }975 }976 ]977 }978});979980await api('https://example.com', {981 context: {982 token: 'secret123'983 }984}).json();985986// Shallow merge: only top-level properties are merged987const instance = ky.create({988 context: {989 a: 1,990 b: {991 nested: true992 }993 }994});995996const extended = instance.extend({997 context: {998 b: {999 updated: true1000 },1001 c: 31002 }1003});1004// Result: {a: 1, b: {updated: true}, c: 3}1005// Note: The original `b.nested` is gone (shallow merge)1006```1007Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1008–1013why, one step back1008### ky.extend(defaultOptions)10091010Create a new `ky` instance with some defaults overridden with your own.10111012In contrast to `ky.create()`, `ky.extend()` inherits defaults from its parent.1013Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d
line 1014why, one step back1014You can pass headers as a `Headers` instance or a plain object. Headers are normalized to a plain object with lowercase names when options are merged, so `init` hooks start with a plain object with lowercase keys. A header removed with `undefined` stays in that object with an `undefined` value.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1015–1042why, one step back10151016You can remove a header with `.extend()` by passing the header with an `undefined` value.1017Passing `undefined` as a string removes the header only if it comes from a `Headers` instance.10181019Similarly, you can remove existing `hooks` entries by extending the hook with an explicit `undefined`.10201021```js1022import ky from 'ky';10231024const url = 'https://sindresorhus.com';10251026const original = ky.create({1027 headers: {1028 rainbow: 'rainbow',1029 unicorn: 'unicorn'1030 },1031 hooks: {1032 beforeRequest: [ () => console.log('before 1') ],1033 afterResponse: [ () => console.log('after 1') ],1034 },1035});10361037const extended = original.extend({1038 headers: {1039 rainbow: undefined1040 },1041 hooks: {1042 beforeRequest: undefined,RefactorSindre Sorhusbefore adoptiona5ed57b
lines 1043–1049why, one step back1043 afterResponse: [1044 ({request}) => {1045 console.log('after 2');1046 console.log(request.headers.has('rainbow'));1047 console.log(request.headers.has('unicorn'));1048 }1049 ],Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1050–1052why, one step back1050 }1051});1052RefactorSindre Sorhusbefore adoptiona5ed57b
line 1053why, one step back1053await extended(url);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1054–1064why, one step back1054//=> after 11055//=> after 21056//=> false1057//=> true1058```10591060You can also refer to parent defaults by providing a function to `.extend()`.10611062```js1063import ky from 'ky';1064Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
line 1065why, one step back1065const api = ky.create({prefix: 'https://example.com/api'});Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 1066why, one step back1066Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
line 1067why, one step back1067const usersApi = api.extend((options) => ({prefix: `${options.prefix}/users`}));Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1068–1075why, one step back10681069const response = await usersApi.get('123');1070//=> 'https://example.com/api/users/123'10711072const response = await api.get('version');1073//=> 'https://example.com/api/version'1074```1075Add `replaceOption` helper for `.extend()` (#846)Sindre Sorhusbefore adoptionbb8412e
lines 1076–1077why, one step back1076By default, `.extend()` deep-merges options: hooks are appended, headers are merged, and search parameters are accumulated. Use [`replaceOption`](#replaceoption) when you want to fully replace a merged property instead.1077Improve docsSindre Sorhusbefore adoption8778439
line 1078why, one step back1078When extending an instance, signals are combined. Use `replaceOption(signal)` to replace inherited signals, or `signal: undefined` to remove them. `null` is accepted for `RequestInit` compatibility and is treated like an absent signal, so it does not remove an inherited signal.Fix `signal` replacement when extending instances (#880)Sindre Sorhusbefore adoption0bda554
line 1079why, one step back1079Add `replaceOption` helper for `.extend()` (#846)Sindre Sorhusbefore adoptionbb8412e
lines 1080–1097why, one step back1080```js1081import ky, {replaceOption} from 'ky';10821083const api = ky.create({1084 hooks: {1085 beforeRequest: [addAuth, addTracking],1086 },1087});10881089// Appends as expected1090const extended = api.extend({hooks: {beforeRequest: [logRequest]}});1091// extended hooks.beforeRequest is [addAuth, addTracking, logRequest]10921093// Replaces instead of appending1094const replaced = api.extend({hooks: replaceOption({beforeRequest: [onlyThis]})});1095// replaced hooks.beforeRequest is [onlyThis]1096```1097Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1098–1099why, one step back1098### ky.create(defaultOptions)1099Readme tweaksSindre Sorhusbefore adoption7f2eade
line 1100why, one step back1100Create a new Ky instance with complete new defaults, without inheriting from any parent instance.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1101–1106why, one step back11011102```js1103import ky from 'ky';11041105// On https://my-site.com1106Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
line 1107why, one step back1107const api = ky.create({baseUrl: 'https://example.com/api/'});Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1108–1111why, one step back11081109const response = await api.get('users/123');1110//=> 'https://example.com/api/users/123'1111Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f
line 1112why, one step back1112const response = await api.get('status', {baseUrl: ''});Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1113–1123why, one step back1113//=> 'https://my-site.com/status'1114```11151116#### defaultOptions11171118Type: `object`11191120### ky.stop11211122A `Symbol` that can be returned by a `beforeRetry` hook to stop the retry. This will also short circuit the remaining `beforeRetry` hooks.1123Explain a missing response and give `extend(fn)` a deep copy of the parent defaultsSindre Sorhusbefore adoption5b7080a
line 1124why, one step back1124Note: 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. Calling one throws a `TypeError` explaining this. 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.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1125–1130why, one step back11251126A 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.11271128```js1129import ky from 'ky';1130Fix docsSindre Sorhusbefore adoptiond4ce7b1
lines 1131–1132why, one step back1131// Note that `response` will be `undefined` in case `ky.stop` is returned.1132const response = await ky.post('https://example.com', {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1133–1142why, one step back1133 hooks: {1134 beforeRetry: [1135 async ({request, options, error, retryCount}) => {1136 const shouldStopRetry = await ky('https://example.com/api');1137 if (shouldStopRetry) {1138 return ky.stop;1139 }1140 }1141 ]1142 }Fix docsSindre Sorhusbefore adoptiond4ce7b1
line 1143why, one step back1143});Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 1144why, one step back1144Explain both causes of a missing response and document the new validationSindre Sorhusbefore adoption58233f1
line 1145why, one step back1145// Using `.text()` or other body methods is not supported, because there is no response to parse.Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
lines 1146–1151why, one step back1146```11471148### ky.retry(options?)11491150Force a retry from an `afterResponse` hook.1151TweaksSindre Sorhusbefore adoption191057d
line 1152why, one step back1152This allows you to retry a request based on the response content, even if the response has a successful status code. The retry will respect the `retry.limit` option and skip the `shouldRetry` check. The forced retry is observable in `beforeRetry` hooks, where the error will be a `ForceRetryError`.Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
line 1153why, one step back1153Explain both causes of a missing response and document the new validationSindre Sorhusbefore adoption58233f1
lines 1154–1155why, one step back1154A marker returned by a second copy of Ky, which happens with a duplicated dependency, is still recognised, the same way the Ky error guards accept branded errors.1155Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
lines 1156–1166why, one step back1156#### options11571158Type: `object`11591160##### delay11611162Type: `number`11631164Custom delay in milliseconds before retrying. If not provided, uses the default retry delay calculation based on `retry.delay` configuration.11651166**Note:** Custom delays bypass jitter and `backoffLimit`. This is intentional, as custom delays often come from server responses (e.g., `Retry-After` headers) and should be respected exactly as specified.Explain both causes of a missing response and document the new validationSindre Sorhusbefore adoption58233f1
line 1167why, one step back1167Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d
line 1168why, one step back1168Must be a non-negative number, `Infinity` included, or `undefined`; anything else makes the request throw a `TypeError` rather than collapsing to a 1ms retry.Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
lines 1169–1175why, one step back11691170##### code11711172Type: `string`11731174Error code for the retry.1175Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d
line 1176why, one step back1176This machine-readable identifier will be included in the error message passed to `beforeRetry` hooks, allowing you to distinguish between different types of forced retries. Anything other than a string makes the request throw a `TypeError`.Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
lines 1177–1190why, one step back11771178```js1179return ky.retry({code: 'RATE_LIMIT'});1180// Resulting error message: 'Forced retry: RATE_LIMIT'1181```11821183##### cause11841185Type: `Error`11861187Original 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.11881189```js1190try {Readme tweaksSindre Sorhusbefore adoption7f2eade
line 1191why, one step back1191 const data = await response.json();Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
lines 1192–1206why, one step back1192 validateBusinessLogic(data);1193} catch (error) {1194 return ky.retry({1195 code: 'VALIDATION_FAILED',1196 cause: error // Preserves original error in chain1197 });1198}1199```12001201##### request12021203Type: `Request`12041205Custom request to use for the retry.1206RefactorSindre Sorhusbefore adoptiona5ed57b
line 1207why, one step back1207This allows you to modify or completely replace the request during a forced retry. The custom request becomes the starting point for the retry - `beforeRetry` hooks can still further modify it if needed. Anything other than a `Request` or `undefined` makes the request throw a `TypeError`.Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
lines 1208–1209why, one step back12081209**Note:** The custom request's `signal` will be replaced with Ky's managed signal to handle timeouts and user-provided abort signals correctly. If the original request body has been consumed, you must provide a new body or clone the request before consuming.TweaksSindre Sorhusbefore adoption8f28eac
lines 1210–1212why, one step back12101211> [!WARNING]1212> Custom retry requests are not sanitized. If you reuse headers across origins, remove any credentials you do not want forwarded.Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
lines 1213–1221why, one step back12131214#### Example12151216```js1217import ky, {isForceRetryError} from 'ky';12181219const api = ky.extend({1220 hooks: {1221 afterResponse: [Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e
line 1222why, one step back1222 async ({request, response}) => {Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
lines 1223–1224why, one step back1223 // Retry based on response body content1224 if (response.status === 200) {Readme tweaksSindre Sorhusbefore adoption7f2eade
line 1225why, one step back1225 const data = await response.json();Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228
lines 1226–1288why, one step back12261227 // Simple retry with default delay1228 if (data.error?.code === 'TEMPORARY_ERROR') {1229 return ky.retry();1230 }12311232 // Retry with custom delay from API response1233 if (data.error?.code === 'RATE_LIMIT') {1234 return ky.retry({1235 delay: data.error.retryAfter * 1000,1236 code: 'RATE_LIMIT'1237 });1238 }12391240 // Retry with a modified request (e.g., fallback endpoint)1241 if (data.error?.code === 'FALLBACK_TO_BACKUP') {1242 return ky.retry({1243 request: new Request('https://backup-api.com/endpoint', {1244 method: request.method,1245 headers: request.headers,1246 }),1247 code: 'BACKUP_ENDPOINT'1248 });1249 }12501251 // Retry with refreshed authentication1252 if (data.error?.code === 'TOKEN_REFRESH' && data.newToken) {1253 return ky.retry({1254 request: new Request(request, {1255 headers: {1256 ...Object.fromEntries(request.headers),1257 'Authorization': `Bearer ${data.newToken}`1258 }1259 }),1260 code: 'TOKEN_REFRESHED'1261 });1262 }12631264 // Retry with cause to preserve error chain1265 try {1266 validateResponse(data);1267 } catch (error) {1268 return ky.retry({1269 code: 'VALIDATION_FAILED',1270 cause: error1271 });1272 }1273 }1274 }1275 ],1276 beforeRetry: [1277 ({error, retryCount}) => {1278 // Observable in beforeRetry hooks1279 if (isForceRetryError(error)) {1280 console.log(`Forced retry #${retryCount}: ${error.message}`);1281 // Example output: "Forced retry #1: Forced retry: RATE_LIMIT"1282 }1283 }1284 ]1285 }1286});12871288const response = await api.get('https://example.com/api');Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1289–1290why, one step back1289```1290Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
lines 1291–1292why, one step back1291### KyError1292Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
line 1293why, one step back1293Base class for all Ky-specific errors. `HTTPError`, `NetworkError`, `TimeoutError`, `ResponseSizeError`, and `ForceRetryError` extend this class.Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
lines 1294–1296why, one step back12941295You 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.1296Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9
lines 1297–1299why, one step back1297> [!NOTE]1298> `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.1299Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
lines 1300–1311why, one step back1300```js1301import ky, {isKyError} from 'ky';13021303try {1304 await ky('https://example.com').json();1305} catch (error) {1306 if (isKyError(error)) {1307 console.log('Ky error:', error.message);1308 }1309}1310```1311Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1312–1315why, one step back1312### HTTPError13131314Exposed 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).1315Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
line 1316why, one step back1316It also has a `data` property with the pre-parsed response body. For JSON responses (based on `Content-Type`), the body is parsed using the [`parseJson` option](#parsejson) if set, or `JSON.parse` by default. For other content types, it is set as plain text. If the body is empty, unreadable, too large, parsing fails, or the error-data read/parse timeout is reached, `data` will be `undefined`. To avoid hanging or excessive buffering, `error.data` body reads and async JSON parsing are bounded by the request timeout (or 10 seconds when `timeout` is disabled), any remaining `totalTimeout` budget, and a 10 MiB response body size limit. If `maxResponseSize` is exceeded while populating `error.data`, Ky throws `ResponseSizeError` instead of `HTTPError`. If `totalTimeout` expires while populating `error.data`, Ky throws `TimeoutError` instead of `HTTPError`. The `data` property is populated before [`beforeError`](#hooks) hooks run, so hooks can access it.Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
line 1317why, one step back1317Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
line 1318why, one step back1318Be 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`](#networkerror) instead of `HTTPError` and will not contain a `response` property.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 1319why, one step back1319Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
line 1320why, one step back1320> [!NOTE]Fix typosSindre Sorhusbefore adoptionbbc98fc
line 1321why, one step back1321> 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.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1322–1323why, one step back13221323```jsAdd `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
line 1324why, one step back1324import ky, {isHTTPError} from 'ky';Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1325–1329why, one step back13251326try {1327 await ky('https://example.com').json();1328} catch (error) {1329 if (isHTTPError(error)) {Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
line 1330why, one step back1330 console.log(error.data);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1331–1337why, one step back1331 }1332}1333```13341335You can also use the `beforeError` hook:13361337```jsMake `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
lines 1338–1339why, one step back1338import ky, {isHTTPError} from 'ky';1339Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1340–1342why, one step back1340await ky('https://example.com', {1341 hooks: {1342 beforeError: [Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e
line 1343why, one step back1343 ({error}) => {Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
line 1344why, one step back1344 if (isHTTPError(error) && error.data !== undefined) {Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
line 1345why, one step back1345 error.message = `${error.message}: ${JSON.stringify(error.data)}`;Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1346–1354why, one step back1346 }13471348 return error;1349 }1350 ]1351 }1352});1353```1354Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c
line 1355why, one step back1355⌨️ **TypeScript:** Accepts an optional [type parameter](https://www.typescriptlang.org/docs/handbook/2/generics.html), which defaults to [`unknown`](https://www.typescriptlang.org/docs/handbook/2/functions.html#unknown), and is passed through to the type of `error.data`.Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9
lines 1356–1377why, one step back13561357### SchemaValidationError13581359The 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.13601361This 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()`.13621363```js1364import ky, {SchemaValidationError} from 'ky';1365import {z} from 'zod';13661367const userSchema = z.object({name: z.string()});13681369try {1370 const user = await ky('/api/user').json(userSchema);1371 console.log(user.name);1372} catch (error) {1373 if (error instanceof SchemaValidationError) {1374 console.error(error.issues);1375 }1376}1377```Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1378–1381why, one step back13781379### TimeoutError13801381The 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).Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
line 1382why, one step back1382Readme tweaksSindre Sorhusbefore adoption7f2eade
lines 1383–1390why, one step back1383```js1384import ky, {isTimeoutError} from 'ky';13851386try {1387 await ky('https://example.com').json();1388} catch (error) {1389 if (isTimeoutError(error)) {1390 console.log('Request timed out');Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458
lines 1391–1406why, one step back1391 }1392}1393```13941395### ResponseSizeError13961397Error thrown when the response body exceeds `maxResponseSize`. It has a `request` property with the `Request` object and a `maxResponseSize` property with the configured limit in bytes.13981399```js1400import ky, {isResponseSizeError} from 'ky';14011402try {1403 await ky('https://example.com/data', {maxResponseSize: 1024}).json();1404} catch (error) {1405 if (isResponseSizeError(error)) {1406 console.log(`Response exceeded ${error.maxResponseSize} bytes`);Readme tweaksSindre Sorhusbefore adoption7f2eade
lines 1407–1410why, one step back1407 }1408}1409```1410Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
lines 1411–1414why, one step back1411### NetworkError14121413The 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.1414Fix a connection dropped while reading the body through shortcuts surfacing as a raw `TypeError`Sindre Sorhusbefore adoption50c3810
line 1415why, one step back1415Network errors are automatically retried (for [retriable methods](#retry)). A connection that drops while a Ky shortcut method like `.json()` is reading the response body is also wrapped in `NetworkError`, but it is not retried because the response has already been received.Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
lines 1416–1430why, one step back14161417> [!NOTE]1418> Network errors are detected using runtime-specific heuristics. Unrecognized runtimes may produce errors that are not wrapped in `NetworkError`. Use the [`shouldRetry`](#retry) option to handle such cases.14191420```js1421import ky, {isNetworkError} from 'ky';14221423try {1424 await ky('https://example.com').json();1425} catch (error) {1426 if (isNetworkError(error)) {1427 console.log('Network error:', error.message);1428 console.log('Original error:', error.cause);1429 }1430}Add `replaceOption` helper for `.extend()` (#846)Sindre Sorhusbefore adoptionbb8412e
lines 1431–1436why, one step back1431```14321433### replaceOption14341435Wraps a value so that [`ky.extend()`](#kyextenddefaultoptions) will replace the parent value instead of merging with it. Works with hooks, headers, search parameters, context, and any other deep-merged option.1436Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33
lines 1437–1438why, one step back1437Inside the `json` option, which holds your own data, use it only where it replaces an inherited value. Ky does not look for it anywhere else there. The `context` option is merged shallowly, so only a wrapper around the whole `context` is supported.1438Add `replaceOption` helper for `.extend()` (#846)Sindre Sorhusbefore adoptionbb8412e
lines 1439–1450why, one step back1439```js1440import ky, {replaceOption} from 'ky';14411442const api = ky.create({1443 headers: {authorization: 'Bearer token', 'x-custom': 'value'},1444});14451446// Replace all headers instead of merging1447const publicApi = api.extend({1448 headers: replaceOption({accept: 'application/json'}),1449});1450// Headers are now just {accept: 'application/json'}Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80
line 1451why, one step back1451```Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1452–1456why, one step back14521453## Tips14541455### Sending form data1456Fix docsSindre Sorhusbefore adoptiond4ce7b1
line 1457why, one step back1457Sending 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`, unless you set a `Content-Type` in the `headers` option, which always takes precedence.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1458–1469why, one step back14581459```js1460import ky from 'ky';14611462// `multipart/form-data`1463const formData = new FormData();1464formData.append('food', 'fries');1465formData.append('drink', 'icetea');14661467const response = await ky.post(url, {body: formData});1468```1469Fix docsSindre Sorhusbefore adoptiond4ce7b1
line 1470why, one step back1470If 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). Like `FormData`, the `Content-Type` is set for you unless you set one in the `headers` option.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1471–1482why, one step back14711472```js1473import ky from 'ky';14741475// `application/x-www-form-urlencoded`1476const searchParams = new URLSearchParams();1477searchParams.set('food', 'fries');1478searchParams.set('drink', 'icetea');14791480const response = await ky.post(url, {body: searchParams});1481```1482Document how to modify `FormData` in `beforeRequest` hooks (#764)Sindre Sorhusbefore adoptiond93560c
lines 1483–1493why, one step back1483#### Modifying FormData in hooks14841485If you need to modify FormData in a `beforeRequest` hook (for example, to transform field names), delete the `Content-Type` header before creating a new `Request`:14861487```js1488import ky from 'ky';14891490const response = await ky.post(url, {1491 body: formData,1492 hooks: {1493 beforeRequest: [Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e
line 1494why, one step back1494 ({request}) => {Document how to modify `FormData` in `beforeRequest` hooks (#764)Sindre Sorhusbefore adoptiond93560c
lines 1495–1511why, one step back1495 const newFormData = new FormData();14961497 // Modify FormData as needed1498 for (const [key, value] of formData) {1499 newFormData.set(key.toLowerCase(), value);1500 }15011502 // Delete `Content-Type` to let Request regenerate it with correct boundary1503 request.headers.delete('content-type');15041505 return new Request(request, {body: newFormData});1506 }1507 ]1508 }1509});1510```1511Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1512–1520why, one step back1512### Setting a custom `Content-Type`15131514Ky 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.15151516```js1517import ky from 'ky';15181519const json = await ky.post('https://example.com', {1520 headers: {Readme tweaksSindre Sorhusbefore adoption7f2eade
line 1521why, one step back1521 'content-type': 'application/x-amz-json-1.1'Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1522–1558why, one step back1522 },1523 json: {1524 foo: true1525 },1526}).json();15271528console.log(json);1529//=> {data: '🦄'}1530```15311532### Cancellation15331534Fetch (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)15351536Example:15371538```js1539import ky from 'ky';15401541const controller = new AbortController();1542const {signal} = controller;15431544setTimeout(() => {1545 controller.abort();1546}, 5000);15471548try {1549 console.log(await ky(url, {signal}).text());1550} catch (error) {1551 if (error.name === 'AbortError') {1552 console.log('Fetch aborted');1553 } else {1554 console.error('Fetch error:', error);1555 }1556}1557```1558Document proxy and HTTP/2 support (#761)Sindre Sorhusbefore adoption3a4457b
lines 1559–1646why, one step back1559### Proxy support (Node.js)15601561#### Native proxy support15621563Node.js 24.5+ supports automatic proxy configuration via environment variables. Set `NODE_USE_ENV_PROXY=1` or use the `--use-env-proxy` CLI flag.15641565```sh1566NODE_USE_ENV_PROXY=1 HTTP_PROXY=http://proxy.example.com:8080 node app.js1567```15681569Or:15701571```sh1572node --use-env-proxy app.js1573```15741575Supported environment variables:1576- `HTTP_PROXY` / `http_proxy`: Proxy URL for HTTP requests1577- `HTTPS_PROXY` / `https_proxy`: Proxy URL for HTTPS requests1578- `NO_PROXY` / `no_proxy`: Comma-separated list of hosts to bypass the proxy15791580#### Using ProxyAgent15811582For more control, use `ProxyAgent` or `EnvHttpProxyAgent` with the `dispatcher` option.15831584```js1585import ky from 'ky';1586import {ProxyAgent} from 'undici';15871588const proxyAgent = new ProxyAgent('http://proxy.example.com:8080');15891590const response = await ky('https://example.com', {1591 dispatcher: proxyAgent1592}).json();1593```15941595Using `EnvHttpProxyAgent` to automatically read proxy settings from environment variables:15961597```js1598import ky from 'ky';1599import {EnvHttpProxyAgent} from 'undici';16001601const proxyAgent = new EnvHttpProxyAgent();16021603const api = ky.extend({1604 dispatcher: proxyAgent1605});16061607const response = await api('https://example.com').json();1608```16091610### HTTP/2 support (Node.js)16111612Undici supports HTTP/2, but it's not enabled by default. Create a custom dispatcher with the `allowH2` option:16131614```js1615import ky from 'ky';1616import {Agent, Pool} from 'undici';16171618const agent = new Agent({1619 factory(origin, options) {1620 return new Pool(origin, {1621 ...options,1622 allowH2: true1623 });1624 }1625});16261627const response = await ky('https://example.com', {1628 dispatcher: agent1629}).json();1630```16311632Combine proxy and HTTP/2:16331634```js1635import ky from 'ky';1636import {ProxyAgent} from 'undici';16371638const proxyAgent = new ProxyAgent({1639 uri: 'http://proxy.example.com:8080',1640 allowH2: true1641});16421643const response = await ky('https://example.com', {1644 dispatcher: proxyAgent1645}).json();1646```Document streaming request body behavior and retry memory implicationsSindre Sorhusbefore adoptionc168a7c
lines 1647–1649why, one step back16471648### Streaming request bodies1649TweaksSindre Sorhusbefore adoption830ab47
line 1650why, one step back1650You can pass a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) as the request body. Ky sets the `duplex: 'half'` option required by the [Fetch spec](https://fetch.spec.whatwg.org/#dom-requestinit-duplex) for you in environments with [request stream support](https://caniuse.com/wf-fetch-request-streams).Document streaming request body behavior and retry memory implicationsSindre Sorhusbefore adoptionc168a7c
lines 1651–1668why, one step back16511652```js1653import ky from 'ky';16541655const stream = new ReadableStream({1656 start(controller) {1657 controller.enqueue(new TextEncoder().encode('hello'));1658 controller.close();1659 },1660});16611662const response = await ky.post('https://example.com/upload', {1663 body: stream,1664});1665```16661667> [!NOTE]1668> When retries are enabled (the default), Ky buffers the entire streaming body in memory to support replaying it. Set `retry: {limit: 0}` to skip this if retries aren't needed.Document proxy and HTTP/2 support (#761)Sindre Sorhusbefore adoption3a4457b
line 1669why, one step back1669Document how to do SSESindre Sorhusbefore adoptionb095178
lines 1670–1684why, one step back1670### Consuming Server-Sent Events (SSE)16711672Use [`parse-sse`](https://github.com/sindresorhus/parse-sse):16731674```js1675import ky from 'ky';1676import {parseServerSentEvents} from 'parse-sse';16771678const response = await ky('https://api.example.com/events');16791680for await (const event of parseServerSentEvents(response)) {1681 console.log(event.data);1682}1683```1684Document paginationSindre Sorhusbefore adoption2481afd
lines 1685–1699why, one step back1685### Pagination16861687Use [`fetch-extras`](https://github.com/sindresorhus/fetch-extras) with Ky for paginating API responses:16881689```js1690import ky from 'ky';1691import {paginate} from 'fetch-extras';16921693const url = 'https://api.github.com/repos/sindresorhus/ky/commits';16941695for await (const commit of paginate(url, {fetchFunction: ky})) {1696 console.log(commit.sha);1697}1698```1699Document type extension patternSindre Sorhusbefore adoption5d3684e
lines 1700–1704why, one step back1700### Extending types17011702Ky's TypeScript types are intentionally defined as type aliases rather than interfaces to prevent global module augmentation, which can lead to type conflicts and unexpected behavior across your codebase. If you need to add custom properties to Ky's types like `KyResponse` or `HTTPError`, create local wrapper types instead:17031704```tsMake `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
line 1705why, one step back1705import ky, {HTTPError, isHTTPError} from 'ky';Document type extension patternSindre Sorhusbefore adoption5d3684e
lines 1706–1710why, one step back17061707interface CustomError extends HTTPError {1708 customProperty: unknown;1709}1710Fix docsSindre Sorhusbefore adoptiond4ce7b1
lines 1711–1713why, one step back1711// Use with type assertion1712let data: unknown;1713Document type extension patternSindre Sorhusbefore adoption5d3684e
lines 1714–1716why, one step back1714const api = ky.extend({1715 hooks: {1716 beforeError: [Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e
line 1717why, one step back1717 async ({error}) => {Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
lines 1718–1719why, one step back1718 if (isHTTPError(error)) {1719 (error as CustomError).customProperty = 'value';Fix docsSindre Sorhusbefore adoptiond4ce7b1
line 1720why, one step back1720 data = (error as CustomError).customProperty;Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b
lines 1721–1722why, one step back1721 }1722Document type extension patternSindre Sorhusbefore adoption5d3684e
lines 1723–1731why, one step back1723 return error;1724 }1725 ]1726 }1727});1728```17291730This approach keeps your types scoped to where they're needed without polluting the global namespace.1731Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1732–1735why, one step back1732## FAQ17331734#### How do I use this in Node.js?1735TweaksSindre Sorhusbefore adoption191057d
line 1736why, one step back1736Node.js supports `fetch` natively, so you can just use this package directly.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1737–1739why, one step back17371738#### How do I use this with a web app (React, Vue.js, etc.) that uses server-side rendering (SSR)?1739Readme tweaksSindre Sorhusbefore adoption7f2eade
line 1740why, one step back1740Node.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`:Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
line 1741why, one step back1741Readme tweaksSindre Sorhusbefore adoption7f2eade
lines 1742–1777why, one step back1742```js1743const api = ky.create({1744 baseUrl: globalThis.window === undefined1745 ? (process.env.BASE_URL ?? 'http://localhost:3000')1746 : undefined,1747});1748```17491750<a name="baseurl-vs-prefix"></a>1751#### What's the difference between `baseUrl` and `prefix`?17521753**`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.17541755**`prefix`** does plain string joining before URL resolution. The leading slash on the input is stripped, so it always appends to the prefix regardless.17561757Use `baseUrl` in almost all cases. Use `prefix` only when you want origin-relative inputs like `/users` to be treated as page-relative.17581759```js1760// On https://example.com17611762// baseUrl: standard URL resolution1763ky('users', {baseUrl: '/api/'});1764//=> https://example.com/api/users17651766ky('/users', {baseUrl: '/api/'});1767//=> https://example.com/users ← leading slash wins176817691770// prefix: always appends1771ky('users', {prefix: '/api'});1772//=> https://example.com/api/users17731774ky('/users', {prefix: '/api'});1775//=> https://example.com/api/users ← leading slash ignored1776```1777Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1778–1779why, one step back1778#### How do I test a browser library that uses this?1779TweaksSindre Sorhusbefore adoption191057d
line 1780why, one step back1780Use a test runner that can run in the browser, like [Vitest](https://vitest.dev/guide/browser/) or [Playwright](https://playwright.dev).Readme tweaksSindre Sorhusbefore adoption7f2eade
lines 1781–1910why, one step back17811782#### How do I add authentication headers to every request?17831784Use the [`beforeRequest` hook](#hooksbeforerequest) to attach headers before each request:17851786```js1787const api = ky.create({1788 hooks: {1789 beforeRequest: [1790 ({request}) => {1791 request.headers.set('Authorization', `Bearer ${getToken()}`);1792 }1793 ]1794 }1795});1796```17971798#### How do I implement token refresh on 401 responses?17991800Configure `retry` to retry on 401, then use the [`beforeRetry` hook](#hooksbeforeretry) to refresh the token:18011802```js1803const api = ky.create({1804 retry: {statusCodes: [401]},1805 hooks: {1806 beforeRetry: [1807 async ({request}) => {1808 const token = await refreshToken();1809 request.headers.set('Authorization', `Bearer ${token}`);1810 }1811 ]1812 }1813});1814```18151816#### How do I mock Ky in tests?18171818Use [MSW](https://mswjs.io) to intercept requests at the network level without modifying your code. Alternatively, pass a custom `fetch` to your Ky instance:18191820```js1821const api = ky.create({1822 fetch: async () => new Response(JSON.stringify({name: 'Test'}), {1823 headers: {1824 'Content-Type': 'application/json'1825 },1826 }),1827});1828```18291830#### How do I retry based on the response body?18311832Use [`ky.retry()`](#kyretryoptions) in an [`afterResponse`](#hooksafterresponse) hook. This lets you force a retry even when the status code is 2xx:18331834```js1835import ky from 'ky';18361837const response = await ky('https://example.com', {1838 hooks: {1839 afterResponse: [1840 async ({response}) => {1841 const data = await response.json();18421843 if (data.status === 'pending') {1844 return ky.retry();1845 }1846 }1847 ]1848 }1849});1850```18511852The retry respects `retry.limit` and is observable in `beforeRetry` hooks.18531854#### How do I stop retrying early?18551856Throw from a `beforeRetry` hook to stop retrying and propagate the error, or return [`ky.stop`](#kystop) to stop silently (the request resolves with `undefined`):18571858```js1859import ky, {isHTTPError} from 'ky';18601861const response = await ky('https://example.com', {1862 hooks: {1863 beforeRetry: [1864 ({error}) => {1865 if (isHTTPError(error) && error.response.status === 400) {1866 throw error; // Stop retrying, propagate the error1867 }1868 }1869 ]1870 }1871});1872```18731874#### How do I only throw on certain HTTP errors?18751876For simple status-based filtering, pass a function to `throwHttpErrors`:18771878```js1879import ky from 'ky';18801881// Only throw on 5xx errors; 4xx responses are returned normally1882const api = ky.create({1883 throwHttpErrors: status => status >= 500,1884});18851886const response = await api('https://example.com/resource');18871888if (response.status === 404) {1889 // Handle "not found" as normal app flow1890}1891```18921893If you need to access the response body in the non-throwing path, use `throwHttpErrors: false` and throw manually in an [`afterResponse`](#hooksafterresponse) hook:18941895```js1896import ky, {HTTPError} from 'ky';18971898const api = ky.create({1899 throwHttpErrors: false,1900 hooks: {1901 afterResponse: [1902 ({request, options, response}) => {1903 if (response.status >= 500) {1904 throw new HTTPError(response, request, options);1905 }1906 }1907 ]1908 }1909});1910```Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1911–1926why, one step back19111912#### How do I use this without a bundler like Webpack?19131914Make 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.19151916```html1917<script type="module">1918import ky from 'https://unpkg.com/ky/distribution/index.js';19191920const json = await ky('https://jsonplaceholder.typicode.com/todos/1').json();19211922console.log(json.title);1923//=> 'delectus aut autem'1924</script>1925```1926TweaksSindre Sorhusbefore adoption191057d
line 1927why, one step back1927#### How is it different from [`got`](https://github.com/sindresorhus/got)?Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1928–1932why, one step back19281929Got is maintained by the same people as Ky, so you probably want Ky instead. It's smaller, works in the browser too, and is more stable since it's built on Fetch.19301931#### How is it different from [`axios`](https://github.com/axios/axios)?1932TweaksSindre Sorhusbefore adoption191057d
line 1933why, one step back1933Axios predates the Fetch API and has a lot of legacy baggage. Ky is built on Fetch, which means it's smaller, more standards-compliant, and works everywhere Fetch does (browsers, Node.js, Bun, Deno). Ky also has a more modern API with better TypeScript support.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1934–1946why, one step back19341935#### What does `ky` mean?19361937It's just a random short npm package name I managed to get. It does, however, have a meaning in Japanese:19381939> 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.19401941## Browser support19421943The latest version of Chrome, Firefox, and Safari.19441945## Node.js support1946TweaksSindre Sorhusbefore adoption191057d
line 1947why, one step back1947Node.js 22 and later.Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1948–1958why, one step back19481949## Related19501951- [fetch-extras](https://github.com/sindresorhus/fetch-extras) - Useful utilities for working with Fetch1952- [ky-hooks-change-case](https://github.com/alice-health/ky-hooks-change-case) - Ky hooks to modify cases on requests and responses of objects19531954## Maintainers19551956- [Sindre Sorhus](https://github.com/sindresorhus)1957- [Seth Holladay](https://github.com/sholladay)1958- [Szymon Marczak](https://github.com/szmarczak)