Skip to content
Myr

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 file

Take 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 back
1<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 back
8 <br>

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 9–28why, one step back
9 <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[![Coverage Status](https://codecov.io/gh/sindresorhus/ky/branch/main/graph/badge.svg)](https://codecov.io/gh/sindresorhus/ky)15[![](https://badgen.net/bundlephobia/minzip/ky)](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 support

Readme tweaksSindre Sorhusbefore adoption7f2eade

line 29why, one step back
29- Upload and download progress

Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f

line 30why, one step back
30- Base URL option

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 31–32why, one step back
31- Instances with custom defaults
32- Hooks

Readme tweaksSindre Sorhusbefore adoption7f2eade

line 33why, one step back
33- Response validation with [Standard Schema](https://standardschema.dev) (Zod, Valibot, etc.)

Fix typosSindre Sorhusbefore adoptionbbc98fc

line 34why, one step back
34- 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 back
35
36## Install3738```sh39npm install ky40```41

Add note about readme being dev versionSindre Sorhusbefore adoption7003a19

lines 42–44why, one step back
42> [!NOTE]
43> This readme is for the next version of Ky. For the current version, [click here](https://www.npmjs.com/package/ky).44

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 45–96why, one step back
45###### CDN
4647- [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).96

Allow `parseJson` to handle empty bodies (#877)Seth Holladaybefore adoption294fe63

line 97why, one step back
97Returns 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 back
98
99Available body shortcuts: `.json()`, `.text()`, `.formData()`, `.arrayBuffer()`, `.blob()`, and `.bytes()`. The `.bytes()` shortcut is only present when the runtime supports `Response.prototype.bytes()`.100

TweaksSindre Sorhusbefore adoption3ded2aa

lines 101–102why, one step back
101Invalid 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.
102

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 103–123why, one step back
103```js
104import 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 back
124```

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 125why, one step back
125

Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9

lines 126–144why, one step back
126You 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```ts

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 145–155why, one step back
145// 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 back
156### ky.query(input, options?)

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 157–167why, one step back
157
158Sets `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).167

TweaksSindre Sorhusbefore adoption830ab47

line 168why, one step back
168When 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 back
169
170#### 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.182

Add QUERY method support (#873)Sindre Sorhusbefore adoption6edddd9

line 183why, one step back
183Internally, 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 back
184
185##### json186187Type: `object` and any other value accepted by [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)188

Fix typos (#852)Rohit Nair Pbefore adoption6d12e2d

line 189why, one step back
189Shortcut 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 back
190

Fix `json` option keeping the content-type inherited from a `Request` input bodySindre Sorhusbefore adoption0f2de47

lines 191–192why, one step back
191The `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.
192

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 193–197why, one step back
193##### searchParams
194195Type: `string | object<string, string | number | boolean | undefined> | Array<Array<string | number | boolean>> | URLSearchParams`\196Default: `''`197

Merge `searchParams` with input URL (#840)AkaHarshitbefore adoption29e78fe

line 198why, one step back
198Search 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 back
199
200Accepts any value supported by [`URLSearchParams()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams).201

Fix a search parameter removed with `undefined` staying in the input URL when a later layer re-adds itSindre Sorhusbefore adoption91ea8a9

line 202why, one step back
202When 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 back
203

Improve docsSindre Sorhusbefore adoption8778439

line 204why, one step back
204When `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 back
205

Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f

line 206why, one step back
206##### baseUrl

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 207–209why, one step back
207
208Type: `string | URL`209

Fix typosSindre Sorhusbefore adoptionbbc98fc

line 210why, one step back
210A 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 back
211

Fix minor typos and improve backtick consistency (#853)Rohit Nair Pbefore adoptiona376fc4

line 212why, one step back
212Useful 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 back
213

Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f

lines 214–217why, one step back
214If 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.217

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 218–222why, one step back
218```js
219import ky from 'ky';220221// On https://example.com222

Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f

lines 223–224why, one step back
223const 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 back
225

Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f

lines 226–227why, one step back
226const 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 back
228```
229

Readme tweaksSindre Sorhusbefore adoption7f2eade

lines 230–231why, one step back
230See [FAQ: `baseUrl` vs `prefix`](#baseurl-vs-prefix)
231

Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f

lines 232–237why, one step back
232##### prefix
233234Type: `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.237

Fix minor typos and improve backtick consistency (#853)Rohit Nair Pbefore adoptiona376fc4

line 238why, one step back
238Useful 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 back
239
240*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.*241

Readme tweaksSindre Sorhusbefore adoption7f2eade

lines 242–243why, one step back
242See [FAQ: `baseUrl` vs `prefix`](#baseurl-vs-prefix)
243

Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f

lines 244–255why, one step back
244```js
245import 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```255

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 256why, one step back
256Notes:

Minor tweaksSindre Sorhusbefore adoption4b37c96

line 257why, one step back
257 - 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 back
258 - 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 back
259
260##### retry261262Type: `object | number`\263Default:264- `limit`: `2`

Add QUERY method support (#873)Sindre Sorhusbefore adoption6edddd9

line 265why, one step back
265- `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 back
266- `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 back
268- `maxRetryAfter`: `Infinity`
269- `backoffLimit`: `Infinity`

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 270why, one step back
270- `delay`: `attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000`

Add `retry.jitter` option (#760)Sindre Sorhusbefore adoption081c924

line 271why, one step back
271- `jitter`: `undefined`

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

lines 272–273why, one step back
272- `retryOnTimeout`: `false`
273- `shouldRetry`: `undefined`

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 274why, one step back
274

Readme tweaksSindre Sorhusbefore adoption7f2eade

line 275why, one step back
275Controls 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 back
276
277If `retry` is a number, it will be used as `limit` and other defaults will remain in place.278

Harden retrySindre Sorhusbefore adoptionc426f19

lines 279–280why, one step back
279`retry.limit`, including numeric shorthand, must be a finite, non-negative integer.
280

Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80

lines 281–282why, one step back
281Network 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.
282

Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8

lines 283–284why, one step back
283A 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.
284

Improve docsSindre Sorhusbefore adoption8778439

line 285why, one step back
285`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 back
286

Skip wrapping a body a hook read, and read a past reset epoch as a timestampSindre Sorhusbefore adoption23ca564

line 287why, one step back
287When 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 back
288

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

lines 289–290why, one step back
289If the retry delay from a retry timing header is greater than `maxRetryAfter`, Ky will use `maxRetryAfter`.
290

Improve docsSindre Sorhusbefore adoption8778439

line 291why, one step back
291The `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 back
292To clamp the delay, set `backoffLimit` to 1000, for example.

Improve docsSindre Sorhusbefore adoption8778439

line 293why, one step back
293A 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 back
294By default, the delay is calculated with `0.3 * (2 ** (attemptCount - 1)) * 1000`. The delay increases exponentially.
295

Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8

line 296why, one step back
296The `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 back
297

Add `retry.jitter` option (#760)Sindre Sorhusbefore adoption081c924

lines 298–299why, one step back
298The `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.
299

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 300why, one step back
300**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 back
301

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 302why, one step back
302The `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 back
303

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

line 304why, one step back
304The `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 back
305
306**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 back
311- `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 back
312- `false` to prevent a retry (no retry will occur)

Fix `shouldRetry` type rejecting functions that return nothingSindre Sorhusbefore adoption178767e

line 313why, one step back
313- `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 back
314
315Returning `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 back
316
317**General example**318

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 319–325why, one step back
319```js
320import 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 back
326 statusCodes: [500],

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 327why, one step back
327 backoffLimit: 3000

Add `retry.jitter` option (#760)Sindre Sorhusbefore adoption081c924

lines 328–331why, one step back
328 }
329}).json();330```331

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

lines 332–333why, one step back
332**Retrying on timeout:**
333

Add `retry.jitter` option (#760)Sindre Sorhusbefore adoption081c924

lines 334–337why, one step back
334```js
335import ky from 'ky';336337const json = await ky('https://example.com', {

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

line 338why, one step back
338 timeout: 5000,

Add `retry.jitter` option (#760)Sindre Sorhusbefore adoption081c924

line 339why, one step back
339 retry: {

Add `retryOnTimeout` and `shouldRetry` options (#767)Sindre Sorhusbefore adoptionf0fdbd4

lines 340–352why, one step back
340 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 back
353 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 back
363 }
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 back
394 }
395}).json();396```397

Document Chromium's automatic retry behavior for 408 status codesSindre Sorhusbefore adoptionec10a68

line 398why, one step back
398> [!NOTE]

Document streaming request body behavior and retry memory implicationsSindre Sorhusbefore adoptionc168a7c

lines 399–401why, one step back
399> 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 back
402> 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.
403

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 404–408why, one step back
404##### timeout
405406Type: `number | false`\407Default: `10000`408

TweaksSindre Sorhusbefore adoption3ded2aa

line 409why, one step back
409Per-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 back
410
411If set to `false`, there will be no per-attempt timeout.412

Explain both causes of a missing response and document the new validationSindre Sorhusbefore adoption58233f1

lines 413–414why, one step back
413If 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.
414

Add `totalTimeout` option and make `timeout` be per retry (#848)Sindre Sorhusbefore adoptionc20d7c7

lines 415–419why, one step back
415##### totalTimeout
416417Type: `number | false`\418Default: `false`419

TweaksSindre Sorhusbefore adoption3ded2aa

line 420why, one step back
420Overall 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 back
421
422`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 back
423
424If 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 back
439

Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458

lines 440–450why, one step back
440##### maxResponseSize
441442Type: `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.450

Improve docsSindre Sorhusbefore adoption8778439

lines 451–452why, one step back
451Responses 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.
452

Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458

lines 453–460why, one step back
453```js
454import ky from 'ky';455456const data = await ky('https://example.com/data', {457 maxResponseSize: 20 * 1024 * 1024,458}).json();459```460

Explain both causes of a missing response and document the new validationSindre Sorhusbefore adoption58233f1

lines 461–470why, one step back
461##### dispatcher
462463An [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.470

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 471–473why, one step back
471##### hooks
472473Type: `object<string, Function[]>`\

Add `init` hook (#841)Sindre Sorhusbefore adoption87c6740

line 474why, one step back
474Default: `{init: [], beforeRequest: [], beforeRetry: [], beforeError: [], afterResponse: []}`

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 475why, one step back
475

Add `init` hook (#841)Sindre Sorhusbefore adoption87c6740

lines 476–477why, one step back
476Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially, unless otherwise noted.
477

Run `beforeError` for a `beforeRetry` abort and share the body-wrapping checkSindre Sorhusbefore adoption55599c8

line 478why, one step back
478Each 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 back
479

Add `init` hook (#841)Sindre Sorhusbefore adoption87c6740

lines 480–484why, one step back
480###### hooks.init
481482Type: `Function[]`\483Default: `[]`484

TweaksSindre Sorhusbefore adoption3ded2aa

line 485why, one step back
485This 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 back
486

Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5

line 487why, one step back
487Ky 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 back
488

TweaksSindre Sorhusbefore adoption3ded2aa

line 489why, one step back
489Unlike 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 back
490

Add `init` hook (#841)Sindre Sorhusbefore adoption87c6740

lines 491–508why, one step back
491A 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 back
509
510###### hooks.beforeRequest511512Type: `Function[]`\513Default: `[]`514

TweaksSindre Sorhusbefore adoption191057d

line 515why, one step back
515This 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 back
516

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

line 517why, one step back
517The `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 back
518

Fix timeouts and user aborts not cancelling a `Request` returned from `beforeRequest` or `beforeRetry` hooksSindre Sorhusbefore adoptione1b088e

line 519why, one step back
519The 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 back
520

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 521–522why, one step back
521Any error thrown by `beforeRequest` hooks is treated as fatal and will not trigger Ky's retry logic.
522

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 523–528why, one step back
523```js
524import 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 back
529 ({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 back
531 }
532 ]533 }534});535536const response = await api.get('https://example.com/api/users');537```538

Document and test URL modification in `beforeRequest` hookSindre Sorhusbefore adoption648e25d

lines 539–558why, one step back
539**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```558

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 559–563why, one step back
559###### hooks.beforeRetry
560561Type: `Function[]`\562Default: `[]`563

TweaksSindre Sorhusbefore adoption191057d

line 564why, one step back
564This 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 back
565

Fix timeouts and user aborts not cancelling a `Request` returned from `beforeRequest` or `beforeRetry` hooksSindre Sorhusbefore adoptione1b088e

line 566why, one step back
566The 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 back
567

TweaksSindre Sorhusbefore adoption8f28eac

lines 568–570why, one step back
568> [!WARNING]
569> Returned `Request` objects are used as-is. If you point one at another origin, remove any credentials you do not want forwarded.570

TweaksSindre Sorhusbefore adoption191057d

line 571why, one step back
571The `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 back
572

Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113

line 573why, one step back
573If 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 back
574
575You 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).576

Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327

lines 577–601why, one step back
577**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```601

Allow `beforeRetry` hooks to return a `Request` or `Response` (#774)Sindre Sorhusbefore adoptiona51bb1e

lines 602–603why, one step back
602**Modifying headers:**
603

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 604–612why, one step back
604```js
605import 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 back
613 }
614 ]615 }616});617```618619**Modifying the request URL:**620621```js

Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c

line 622why, one step back
622import ky, {isHTTPError} from 'ky';

Allow `beforeRetry` hooks to return a `Request` or `Response` (#774)Sindre Sorhusbefore adoptiona51bb1e

lines 623–626why, one step back
623
624const 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 back
627 ({request, error}) => {

Allow `beforeRetry` hooks to return a `Request` or `Response` (#774)Sindre Sorhusbefore adoptiona51bb1e

line 628why, one step back
628 // Add query parameters based on error response

Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c

lines 629–634why, one step back
629 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 back
635 const url = new URL(request.url);

Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c

line 636why, one step back
636 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 back
637 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 back
658 }
659 ]660 }661});662```663664###### hooks.beforeError665666Type: `Function[]`\667Default: `[]`668

Fix typosSindre Sorhusbefore adoptionbbc98fc

line 669why, one step back
669This 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 back
670

Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458

line 671why, one step back
671This 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 back
672

Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458

lines 673–674why, one step back
673Errors 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.
674

Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e

line 675why, one step back
675The `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 back
676
677If 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 back
678
679```js

Add `request` and `options` to `beforeError` hook state (#835)Sindre Sorhusbefore adoption01e0b85

line 680why, one step back
680import ky, {isHTTPError} from 'ky';

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 681–684why, one step back
681
682await ky('https://example.com', {683 hooks: {684 beforeError: [

Add `request` and `options` to `beforeError` hook state (#835)Sindre Sorhusbefore adoption01e0b85

line 685why, one step back
685 ({request, options, error}) => {

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

lines 686–694why, one step back
686 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 back
695 }
696

Add `request` and `options` to `beforeError` hook state (#835)Sindre Sorhusbefore adoption01e0b85

lines 697–698why, one step back
697 // `request` and `options` are always available
698 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 back
699
700 return error;701 }702 ]703 }704});705```706707###### hooks.afterResponse708709Type: `Function[]`\710Default: `[]`711

Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e

line 712why, one step back
712This 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 back
713

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

line 714why, one step back
714You 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 back
715

TweaksSindre Sorhusbefore adoption8f28eac

lines 716–718why, one step back
716> [!WARNING]
717> `ky.retry({request})` uses the replacement request as-is. If it targets another origin, remove any credentials you do not want forwarded.718

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

line 719why, one step back
719Any 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 back
720

TweaksSindre Sorhusbefore adoption191057d

line 721why, one step back
721The `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 back
722
723```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 back
729 ({response}) => {

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 730–736why, one step back
730 // 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 },736

Add 401 token refresh pattern tests and examplesSindre Sorhusbefore adoption337a1b2

line 737why, one step back
737 // Or retry with a fresh token on a 401 error

Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e

lines 738–739why, one step back
738 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 back
740 // Only refresh on first 401, not on subsequent retries
741 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 back
742

Add 401 token refresh pattern tests and examplesSindre Sorhusbefore adoption337a1b2

lines 743–744why, one step back
743 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 back
745

Add 401 token refresh pattern tests and examplesSindre Sorhusbefore adoption337a1b2

lines 746–749why, one step back
746 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 back
750 }
751 },752

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

line 753why, one step back
753 // Or force retry based on response body content

Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e

line 754why, one step back
754 async ({response}) => {

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

line 755why, one step back
755 if (response.status === 200) {

Readme tweaksSindre Sorhusbefore adoption7f2eade

line 756why, one step back
756 const data = await response.json();

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

lines 757–766why, one step back
757 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 },766

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 767why, one step back
767 // Or show a notification only on the last retry for 5xx errors

Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e

line 768why, one step back
768 ({options, response, retryCount}) => {

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 769–781why, one step back
769 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##### throwHttpErrors781

Allow `throwHttpErrors` option to be a function (#781)Sindre Sorhusbefore adoption84ff3b9

line 782why, one step back
782Type: `boolean | (status: number) => boolean`\

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 783–787why, one step back
783Default: `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 back
788
789You 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 back
790
791Note: If `false`, error responses are considered successful and the request will not be retried.792

Don't throw `HTTPError` for opaque responses from `no-cors` requests (#847)Sindre Sorhusbefore adoption1d15eb6

lines 793–794why, one step back
793Note: [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.
794

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 795–801why, one step back
795##### onDownloadProgress
796797Type: `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 back
802- `progress` is an object with these properties:

Readme tweaksSindre Sorhusbefore adoption7f2eade

lines 803–804why, one step back
803 - `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 back
805 - `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 back
807

Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d

line 808why, one step back
808`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 back
809

Explain both causes of a missing response and document the new validationSindre Sorhusbefore adoption58233f1

line 810why, one step back
810Responses 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 back
811

Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5

line 812why, one step back
812Do 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 back
813

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 814–831why, one step back
814```js
815import 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.831

Gracefully ignore `onUploadProgress` when request streams are unsupported (#845)Sindre Sorhusbefore adoption1e38ff4

line 832why, one step back
832> [!NOTE]

Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327

line 833why, one step back
833> 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 back
834

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 835why, one step back
835The function receives these arguments:

Gracefully ignore `onUploadProgress` when request streams are unsupported (#845)Sindre Sorhusbefore adoption1e38ff4

line 836why, one step back
836- `progress` is an object with these properties:

Readme tweaksSindre Sorhusbefore adoption7f2eade

lines 837–838why, one step back
837 - `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 back
839 - `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 back
841

Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5

lines 842–844why, one step back
842A `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 back
845
846```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.865

Add request/response context to `parseJson` option (#849)Sindre Sorhusbefore adoption3713ce8

lines 866–867why, one step back
866The 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)).
867

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 868–870why, one step back
868Use-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 back
8713. 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 back
872
873```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 back
879}).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 back
890}).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 back
924Has 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 back
925
926Use-cases:

TweaksSindre Sorhusbefore adoption191057d

lines 927–928why, one step back
9271. 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 back
929
930```js931import ky from 'ky';932

TweaksSindre Sorhusbefore adoption191057d

lines 933–943why, one step back
933const 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 back
944```
945

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 946–969why, one step back
946##### context
947948Type: `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 back
970 ({request, options}) => {

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 971–1007why, one step back
971 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```1007

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1008–1013why, one step back
1008### 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.1013

Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d

line 1014why, one step back
1014You 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 back
1015
1016You 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 back
1043 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 back
1050 }
1051});1052

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1053why, one step back
1053await extended(url);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1054–1064why, one step back
1054//=> after 1
1055//=> after 21056//=> false1057//=> true1058```10591060You can also refer to parent defaults by providing a function to `.extend()`.10611062```js1063import ky from 'ky';1064

Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f

line 1065why, one step back
1065const api = ky.create({prefix: 'https://example.com/api'});

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 1066why, one step back
1066

Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f

line 1067why, one step back
1067const 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 back
1068
1069const 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```1075

Add `replaceOption` helper for `.extend()` (#846)Sindre Sorhusbefore adoptionbb8412e

lines 1076–1077why, one step back
1076By 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.
1077

Improve docsSindre Sorhusbefore adoption8778439

line 1078why, one step back
1078When 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 back
1079

Add `replaceOption` helper for `.extend()` (#846)Sindre Sorhusbefore adoptionbb8412e

lines 1080–1097why, one step back
1080```js
1081import 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```1097

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1098–1099why, one step back
1098### ky.create(defaultOptions)
1099

Readme tweaksSindre Sorhusbefore adoption7f2eade

line 1100why, one step back
1100Create 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 back
1101
1102```js1103import ky from 'ky';11041105// On https://my-site.com1106

Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f

line 1107why, one step back
1107const 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 back
1108
1109const response = await api.get('users/123');1110//=> 'https://example.com/api/users/123'1111

Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f

line 1112why, one step back
1112const response = await api.get('status', {baseUrl: ''});

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1113–1123why, one step back
1113//=> '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.1123

Explain a missing response and give `extend(fn)` a deep copy of the parent defaultsSindre Sorhusbefore adoption5b7080a

line 1124why, one step back
1124Note: 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 back
1125
1126A 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';1130

Fix docsSindre Sorhusbefore adoptiond4ce7b1

lines 1131–1132why, one step back
1131// 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 back
1133 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 back
1143});

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

line 1144why, one step back
1144

Explain both causes of a missing response and document the new validationSindre Sorhusbefore adoption58233f1

line 1145why, one step back
1145// 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 back
1146```
11471148### ky.retry(options?)11491150Force a retry from an `afterResponse` hook.1151

TweaksSindre Sorhusbefore adoption191057d

line 1152why, one step back
1152This 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 back
1153

Explain both causes of a missing response and document the new validationSindre Sorhusbefore adoption58233f1

lines 1154–1155why, one step back
1154A 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.
1155

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

lines 1156–1166why, one step back
1156#### options
11571158Type: `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 back
1167

Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d

line 1168why, one step back
1168Must 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 back
1169
1170##### code11711172Type: `string`11731174Error code for the retry.1175

Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d

line 1176why, one step back
1176This 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 back
1177
1178```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 back
1191 const data = await response.json();

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

lines 1192–1206why, one step back
1192 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.1206

RefactorSindre Sorhusbefore adoptiona5ed57b

line 1207why, one step back
1207This 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 back
1208
1209**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 back
1210
1211> [!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 back
1213
1214#### 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 back
1222 async ({request, response}) => {

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

lines 1223–1224why, one step back
1223 // Retry based on response body content
1224 if (response.status === 200) {

Readme tweaksSindre Sorhusbefore adoption7f2eade

line 1225why, one step back
1225 const data = await response.json();

Add `ky.retry()` to force retries from `afterResponse` hooks (#779)Sindre Sorhusbefore adoption68a5228

lines 1226–1288why, one step back
1226
1227 // 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 back
1289```
1290

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

lines 1291–1292why, one step back
1291### KyError
1292

Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458

line 1293why, one step back
1293Base 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 back
1294
1295You 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.1296

Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9

lines 1297–1299why, one step back
1297> [!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.1299

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

lines 1300–1311why, one step back
1300```js
1301import 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```1311

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1312–1315why, one step back
1312### HTTPError
13131314Exposed 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).1315

Add `maxResponseSize` optionSindre Sorhusbefore adoption0d59458

line 1316why, one step back
1316It 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 back
1317

Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80

line 1318why, one step back
1318Be 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 back
1319

Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c

line 1320why, one step back
1320> [!NOTE]

Fix typosSindre Sorhusbefore adoptionbbc98fc

line 1321why, one step back
1321> 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 back
1322
1323```js

Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c

line 1324why, one step back
1324import ky, {isHTTPError} from 'ky';

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1325–1329why, one step back
1325
1326try {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 back
1330 console.log(error.data);

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1331–1337why, one step back
1331 }
1332}1333```13341335You can also use the `beforeError` hook:13361337```js

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

lines 1338–1339why, one step back
1338import ky, {isHTTPError} from 'ky';
1339

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1340–1342why, one step back
1340await ky('https://example.com', {
1341 hooks: {1342 beforeError: [

Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e

line 1343why, one step back
1343 ({error}) => {

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

line 1344why, one step back
1344 if (isHTTPError(error) && error.data !== undefined) {

Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c

line 1345why, one step back
1345 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 back
1346 }
13471348 return error;1349 }1350 ]1351 }1352});1353```1354

Add `data` property to `HTTPError` with pre-parsed response body (#823)Sindre Sorhusbefore adoption1341f5c

line 1355why, one step back
1355⌨️ **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 back
1356
1357### 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 back
1378
1379### 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 back
1382

Readme tweaksSindre Sorhusbefore adoption7f2eade

lines 1383–1390why, one step back
1383```js
1384import 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 back
1391 }
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 back
1407 }
1408}1409```1410

Add `NetworkError` class and tighten retry logic (#842)Sindre Sorhusbefore adoptioneaf0b80

lines 1411–1414why, one step back
1411### NetworkError
14121413The 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.1414

Fix a connection dropped while reading the body through shortcuts surfacing as a raw `TypeError`Sindre Sorhusbefore adoption50c3810

line 1415why, one step back
1415Network 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 back
1416
1417> [!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 back
1431```
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.1436

Release the body when a predicate throws, an abort wins, or a response cannot be decoratedSindre Sorhusbefore adoptiondeb5a33

lines 1437–1438why, one step back
1437Inside 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.
1438

Add `replaceOption` helper for `.extend()` (#846)Sindre Sorhusbefore adoptionbb8412e

lines 1439–1450why, one step back
1439```js
1440import 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 back
1451```

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1452–1456why, one step back
1452
1453## Tips14541455### Sending form data1456

Fix docsSindre Sorhusbefore adoptiond4ce7b1

line 1457why, one step back
1457Sending 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 back
1458
1459```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```1469

Fix docsSindre Sorhusbefore adoptiond4ce7b1

line 1470why, one step back
1470If 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 back
1471
1472```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```1482

Document how to modify `FormData` in `beforeRequest` hooks (#764)Sindre Sorhusbefore adoptiond93560c

lines 1483–1493why, one step back
1483#### Modifying FormData in hooks
14841485If 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 back
1494 ({request}) => {

Document how to modify `FormData` in `beforeRequest` hooks (#764)Sindre Sorhusbefore adoptiond93560c

lines 1495–1511why, one step back
1495 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```1511

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1512–1520why, one step back
1512### 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 back
1521 '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 back
1522 },
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```1558

Document proxy and HTTP/2 support (#761)Sindre Sorhusbefore adoption3a4457b

lines 1559–1646why, one step back
1559### 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 back
1647
1648### Streaming request bodies1649

TweaksSindre Sorhusbefore adoption830ab47

line 1650why, one step back
1650You 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 back
1651
1652```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 back
1669

Document how to do SSESindre Sorhusbefore adoptionb095178

lines 1670–1684why, one step back
1670### 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```1684

Document paginationSindre Sorhusbefore adoption2481afd

lines 1685–1699why, one step back
1685### Pagination
16861687Use [`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```1699

Document type extension patternSindre Sorhusbefore adoption5d3684e

lines 1700–1704why, one step back
1700### Extending types
17011702Ky'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```ts

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

line 1705why, one step back
1705import ky, {HTTPError, isHTTPError} from 'ky';

Document type extension patternSindre Sorhusbefore adoption5d3684e

lines 1706–1710why, one step back
1706
1707interface CustomError extends HTTPError {1708 customProperty: unknown;1709}1710

Fix docsSindre Sorhusbefore adoptiond4ce7b1

lines 1711–1713why, one step back
1711// Use with type assertion
1712let data: unknown;1713

Document type extension patternSindre Sorhusbefore adoption5d3684e

lines 1714–1716why, one step back
1714const api = ky.extend({
1715 hooks: {1716 beforeError: [

Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e

line 1717why, one step back
1717 async ({error}) => {

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

lines 1718–1719why, one step back
1718 if (isHTTPError(error)) {
1719 (error as CustomError).customProperty = 'value';

Fix docsSindre Sorhusbefore adoptiond4ce7b1

line 1720why, one step back
1720 data = (error as CustomError).customProperty;

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

lines 1721–1722why, one step back
1721 }
1722

Document type extension patternSindre Sorhusbefore adoption5d3684e

lines 1723–1731why, one step back
1723 return error;
1724 }1725 ]1726 }1727});1728```17291730This approach keeps your types scoped to where they're needed without polluting the global namespace.1731

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1732–1735why, one step back
1732## FAQ
17331734#### How do I use this in Node.js?1735

TweaksSindre Sorhusbefore adoption191057d

line 1736why, one step back
1736Node.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 back
1737
1738#### How do I use this with a web app (React, Vue.js, etc.) that uses server-side rendering (SSR)?1739

Readme tweaksSindre Sorhusbefore adoption7f2eade

line 1740why, one step back
1740Node.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 back
1741

Readme tweaksSindre Sorhusbefore adoption7f2eade

lines 1742–1777why, one step back
1742```js
1743const 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```1777

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1778–1779why, one step back
1778#### How do I test a browser library that uses this?
1779

TweaksSindre Sorhusbefore adoption191057d

line 1780why, one step back
1780Use 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 back
1781
1782#### 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 back
1911
1912#### 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```1926

TweaksSindre Sorhusbefore adoption191057d

line 1927why, one step back
1927#### 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 back
1928
1929Got 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)?1932

TweaksSindre Sorhusbefore adoption191057d

line 1933why, one step back
1933Axios 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 back
1934
1935#### 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 support1946

TweaksSindre Sorhusbefore adoption191057d

line 1947why, one step back
1947Node.js 22 and later.

Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250

lines 1948–1958why, one step back
1948
1949## 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)