readme.md
This file
Path
readme.md
1,958 lines · 73.6 KiB · Markdown
Last changed by
Let a `beforeRetry` hook change per-attempt optionsSindre Sorhusbefore adoption242c327
History of this fileTake it
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>8 <br>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[](https://codecov.io/gh/sindresorhus/ky)15[](https://bundlephobia.com/result?p=ky)1617Ky targets [modern browsers](#browser-support), Node.js, Bun, and Deno.1819It's just a tiny package with no dependencies.2021## Benefits over plain `fetch`2223- Simpler API24- Method shortcuts (`ky.post()`)25- Treats non-2xx status codes as errors (after redirects)26- Retries failed requests27- JSON option28- Timeout support29- Upload and download progress30- Base URL option31- Instances with custom defaults32- Hooks33- Response validation with [Standard Schema](https://standardschema.dev) (Zod, Valibot, etc.)34- TypeScript niceties (e.g., `.json()` supports generics and defaults to `unknown`, not `any`)3536## Install3738```sh39npm install ky40```4142> [!NOTE]43> This readme is for the next version of Ky. For the current version, [click here](https://www.npmjs.com/package/ky).4445###### CDN4647- [jsdelivr](https://cdn.jsdelivr.net/npm/ky/+esm)48- [unpkg](https://unpkg.com/ky)49- [esm.sh](https://esm.sh/ky)5051## Usage5253```js54import ky from 'ky';5556const json = await ky.post('https://example.com', {json: {foo: true}}).json();5758console.log(json);59//=> {data: '🦄'}60```6162With plain `fetch`, it would be:6364```js65class HTTPError extends Error {}6667const response = await fetch('https://example.com', {68 method: 'POST',69 body: JSON.stringify({foo: true}),70 headers: {71 'content-type': 'application/json'72 }73});7475if (!response.ok) {76 throw new HTTPError(`Fetch error: ${response.statusText}`);77}7879const json = await response.json();8081console.log(json);82//=> {data: '🦄'}83```8485If you are using [Deno](https://github.com/denoland/deno), import Ky from a URL. For example, using a CDN:8687```js88import ky from 'https://esm.sh/ky';89```9091## API9293### ky(input, options?)9495The `input` and `options` are the same as [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch), with additional `options` available (see below).9697Returns 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.9899Available body shortcuts: `.json()`, `.text()`, `.formData()`, `.arrayBuffer()`, `.blob()`, and `.bytes()`. The `.bytes()` shortcut is only present when the runtime supports `Response.prototype.bytes()`.100101Invalid 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.102103```js104import ky from 'ky';105106const user = await ky('/api/user').json();107108console.log(user);109```110111⌨️ **TypeScript:** Accepts an optional [type parameter](https://www.typescriptlang.org/docs/handbook/2/generics.html), which defaults to [`unknown`](https://www.typescriptlang.org/docs/handbook/2/functions.html#unknown), and is passed through to the return type of `.json()`.112113```ts114import ky from 'ky';115116// user1 is unknown117const user1 = await ky('/api/users/1').json();118// user2 is a User119const user2 = await ky<User>('/api/users/2').json();120// user3 is a User121const user3 = await ky('/api/users/3').json<User>();122123console.log([user1, user2, user3]);124```125126You 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```ts145// 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?)156### ky.query(input, options?)157158Sets `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).167168When 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.169170#### 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.182183Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD`, `DELETE`, and `QUERY`) are uppercased in order to avoid server errors due to case sensitivity.184185##### json186187Type: `object` and any other value accepted by [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)188189Shortcut 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.190191The `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.192193##### searchParams194195Type: `string | object<string, string | number | boolean | undefined> | Array<Array<string | number | boolean>> | URLSearchParams`\196Default: `''`197198Search parameters to include in the request URL. Setting this will merge with any existing search parameters in the input URL.199200Accepts any value supported by [`URLSearchParams()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams).201202When 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'`.203204When `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.205206##### baseUrl207208Type: `string | URL`209210A 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`.211212Useful when used with [`ky.extend()`](#kyextenddefaultoptions) to create niche-specific Ky instances.213214If 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.217218```js219import ky from 'ky';220221// On https://example.com222223const response = await ky('users', {baseUrl: '/api/'});224//=> 'https://example.com/api/users'225226const response = await ky('/users', {baseUrl: '/api/'});227//=> 'https://example.com/users'228```229230See [FAQ: `baseUrl` vs `prefix`](#baseurl-vs-prefix)231232##### prefix233234Type: `string | URL`235236A prefix to prepend to the `input` before making the request (and before it is resolved against the `baseUrl`). It can be any valid path or URL, either relative or absolute. A trailing slash `/` is optional and will be added automatically, if needed, when it is joined with `input`. Only takes effect when `input` is a string.237238Useful when used with [`ky.extend()`](#kyextenddefaultoptions) to create niche-specific Ky instances.239240*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.*241242See [FAQ: `baseUrl` vs `prefix`](#baseurl-vs-prefix)243244```js245import ky from 'ky';246247// On https://example.com248249const response = await ky('users', {prefix: '/api/'});250//=> 'https://example.com/api/users'251252const response = await ky('/users', {prefix: '/api/'});253//=> 'https://example.com/api/users'254```255256Notes: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`.258 - After `prefix` and `input` are joined, the result is resolved against the `baseUrl` option, if present.259260##### retry261262Type: `object | number`\263Default:264- `limit`: `2`265- `methods`: `get` `put` `head` `delete` `options` `trace` `query`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)268- `maxRetryAfter`: `Infinity`269- `backoffLimit`: `Infinity`270- `delay`: `attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000`271- `jitter`: `undefined`272- `retryOnTimeout`: `false`273- `shouldRetry`: `undefined`274275Controls retry behavior. Each field is documented individually below.276277If `retry` is a number, it will be used as `limit` and other defaults will remain in place.278279`retry.limit`, including numeric shorthand, must be a finite, non-negative integer.280281Network 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.282283A 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.284285`413 Payload Too Large` is only retried when the response includes a retry timing header, unless `shouldRetry` returns `true`.286287When 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.288289If the retry delay from a retry timing header is greater than `maxRetryAfter`, Ky will use `maxRetryAfter`.290291The `backoffLimit` option is the upper limit of the delay per retry in milliseconds, for the delay calculated by `retry.delay`.292To clamp the delay, set `backoffLimit` to 1000, for example.293A delay from a retry timing header is not subject to this limit; use `maxRetryAfter` to bound it.294By default, the delay is calculated with `0.3 * (2 ** (attemptCount - 1)) * 1000`. The delay increases exponentially.295296The `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.297298The `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.299300**Note:** Jitter is not applied when the server provides a retry timing header, as the server's explicit timing should be respected.301302The `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.303304The `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.305306**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:311- `true` to force a retry (bypasses `retryOnTimeout`, status code checks, and other default validations)312- `false` to prevent a retry (no retry will occur)313- `undefined` (or nothing) to use the default retry logic (`retryOnTimeout`, status codes, network errors). Unrecognized error types are not retried.314315Returning `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.316317**General example**318319```js320import ky from 'ky';321322const json = await ky('https://example.com', {323 retry: {324 limit: 10,325 methods: ['get'],326 statusCodes: [500],327 backoffLimit: 3000328 }329}).json();330```331332**Retrying on timeout:**333334```js335import ky from 'ky';336337const json = await ky('https://example.com', {338 timeout: 5000,339 retry: {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: {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)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 }394 }395}).json();396```397398> [!NOTE]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]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.403404##### timeout405406Type: `number | false`\407Default: `10000`408409Per-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).410411If set to `false`, there will be no per-attempt timeout.412413If 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.414415##### totalTimeout416417Type: `number | false`\418Default: `false`419420Overall 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`.421422`beforeError` hooks run after an error is produced and are not bounded by `totalTimeout`.423424If 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```439440##### maxResponseSize441442Type: `number`\443Default: `Infinity`444445Maximum response body size in bytes. Must be a non-negative safe integer or `Infinity`. Set to `0` to allow only empty bodies.446447The limit counts bytes from the response stream after decompression, independently of `Content-Length`. It applies as the body is consumed, including in `afterResponse` hooks and for responses returned by hooks. Exceeding the limit cancels the stream and throws a `ResponseSizeError`, without automatically retrying.448449With `await ky(url)`, the response can resolve before the limit is exceeded; the body read will reject instead. This limits body bytes, not total memory usage. Parsing, buffering, and concurrent requests can use additional memory.450451Responses 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.452453```js454import ky from 'ky';455456const data = await ky('https://example.com/data', {457 maxResponseSize: 20 * 1024 * 1024,458}).json();459```460461##### dispatcher462463An [undici](https://github.com/nodejs/undici) `Agent` or `Dispatcher`, forwarded to `fetch()` as-is. Ky does not use it, it just passes it through.464465##### next466467A framework-specific fetch extension, such as [Next.js's `next`](https://nextjs.org/docs/app/api-reference/functions/next#options), forwarded to `fetch()` as-is.468469Ky forwards every option it does not recognize to `fetch()`. The type of such an option comes from the global `RequestInit` type, which `@types/node` extends with `dispatcher` and Next.js extends with `next`. An extension that your environment does not declare needs a type assertion.470471##### hooks472473Type: `object<string, Function[]>`\474Default: `{init: [], beforeRequest: [], beforeRetry: [], beforeError: [], afterResponse: []}`475476Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially, unless otherwise noted.477478Each 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.479480###### hooks.init481482Type: `Function[]`\483Default: `[]`484485This 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.486487Ky 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.488489Unlike other hooks, `init` hooks are synchronous. An error thrown by one rejects the returned promise and is not passed to `beforeError` hooks.490491A 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```509510###### hooks.beforeRequest511512Type: `Function[]`\513Default: `[]`514515This 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.516517The `retryCount` is always `0`, since `beforeRequest` hooks run once before retry handling begins.518519The 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.520521Any error thrown by `beforeRequest` hooks is treated as fatal and will not trigger Ky's retry logic.522523```js524import ky from 'ky';525526const api = ky.extend({527 hooks: {528 beforeRequest: [529 ({request}) => {530 request.headers.set('Authorization', 'token initial-token');531 }532 ]533 }534});535536const response = await api.get('https://example.com/api/users');537```538539**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```558559###### hooks.beforeRetry560561Type: `Function[]`\562Default: `[]`563564This 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.565566The 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.567568> [!WARNING]569> Returned `Request` objects are used as-is. If you point one at another origin, remove any credentials you do not want forwarded.570571The `retryCount` is always `>= 1`, since this hook is only called during retries, not on the initial request.572573If 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`.574575You 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).576577**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```601602**Modifying headers:**603604```js605import ky from 'ky';606607const response = await ky('https://example.com', {608 hooks: {609 beforeRetry: [610 async ({request, options, error, retryCount}) => {611 const token = await ky('https://example.com/refresh-token');612 request.headers.set('Authorization', `token ${token}`);613 }614 ]615 }616});617```618619**Modifying the request URL:**620621```js622import ky, {isHTTPError} from 'ky';623624const response = await ky('https://example.com/api', {625 hooks: {626 beforeRetry: [627 ({request, error}) => {628 // Add query parameters based on error response629 if (630 isHTTPError(error)631 && typeof error.data === 'object'632 && error.data !== null633 && 'processId' in error.data634 ) {635 const url = new URL(request.url);636 url.searchParams.set('processId', String(error.data.processId));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 }658 }659 ]660 }661});662```663664###### hooks.beforeError665666Type: `Function[]`\667Default: `[]`668669This 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.670671This 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.672673Errors 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.674675The `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).676677If 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`.678679```js680import ky, {isHTTPError} from 'ky';681682await ky('https://example.com', {683 hooks: {684 beforeError: [685 ({request, options, error}) => {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 }695 }696697 // `request` and `options` are always available698 console.log(`Request to ${request.url} failed`, options.context);699700 return error;701 }702 ]703 }704});705```706707###### hooks.afterResponse708709Type: `Function[]`\710Default: `[]`711712This 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).713714You 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.715716> [!WARNING]717> `ky.retry({request})` uses the replacement request as-is. If it targets another origin, remove any credentials you do not want forwarded.718719Any non-`ky.retry()` error thrown by `afterResponse` hooks is treated as fatal and will not trigger Ky's retry logic.720721The `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).722723```js724import ky from 'ky';725726const response = await ky('https://example.com', {727 hooks: {728 afterResponse: [729 ({response}) => {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 },736737 // Or retry with a fresh token on a 401 error738 async ({request, response, retryCount}) => {739 if (response.status === 401 && retryCount === 0) {740 // Only refresh on first 401, not on subsequent retries741 const {token} = await ky.post('https://example.com/auth/refresh').json();742743 const headers = new Headers(request.headers);744 headers.set('Authorization', `Bearer ${token}`);745746 return ky.retry({747 request: new Request(request, {headers}),748 code: 'TOKEN_REFRESHED'749 });750 }751 },752753 // Or force retry based on response body content754 async ({response}) => {755 if (response.status === 200) {756 const data = await response.json();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 },766767 // Or show a notification only on the last retry for 5xx errors768 ({options, response, retryCount}) => {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##### throwHttpErrors781782Type: `boolean | (status: number) => boolean`\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.788789You 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.790791Note: If `false`, error responses are considered successful and the request will not be retried.792793Note: [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.794795##### onDownloadProgress796797Type: `Function`798799Download progress event handler.800801The function receives these arguments:802- `progress` is an object with these properties:803 - `percent` is a number between 0 and 1 representing the progress percentage.804 - `transferredBytes` is the number of bytes transferred so far.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.807808`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.809810Responses 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.811812Do 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.813814```js815import ky from 'ky';816817const response = await ky('https://example.com', {818 onDownloadProgress: (progress, chunk) => {819 // Example output:820 // `100% - 1271 of 1271 bytes`821 console.log(`${progress.percent * 100}% - ${progress.transferredBytes} of ${progress.totalBytes} bytes`);822 }823});824```825826##### onUploadProgress827828Type: `Function`829830Upload progress event handler.831832> [!NOTE]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.834835The function receives these arguments:836- `progress` is an object with these properties:837 - `percent` is a number between 0 and 1 representing the progress percentage.838 - `transferredBytes` is the number of bytes transferred so far.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.841842A `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.845846```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.865866The 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)).867868Use-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).8713. Log or handle JSON parse errors with request context.872873```js874import ky from 'ky';875import bourne from '@hapijs/bourne';876877const json = await ky('https://example.com', {878 parseJson: text => bourne(text)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 }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.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.925926Use-cases: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.929930```js931import ky from 'ky';932933const 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();944```945946##### context947948Type: `object<string, unknown>`\949Default: `{}`950951User-defined data passed to hooks.952953This option allows you to pass arbitrary contextual data to hooks without polluting the request itself. The context is available in all hooks and is **guaranteed to always be an object** (never `undefined`), so you can safely access properties without optional chaining.954955Use cases:956- Pass authentication tokens or API keys to hooks957- Attach request metadata for logging or debugging958- Implement conditional logic in hooks based on the request context959- Pass serverless environment bindings (e.g., Cloudflare Workers)960961**Note:** Context is shallow merged. Top-level properties are merged, but nested objects are replaced. Only enumerable properties are copied.962963```js964import ky from 'ky';965966// Pass data to hooks967const api = ky.create({968 hooks: {969 beforeRequest: [970 ({request, options}) => {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```10071008### 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.10131014You 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.10151016You 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,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 ],1050 }1051});10521053await extended(url);1054//=> after 11055//=> after 21056//=> false1057//=> true1058```10591060You can also refer to parent defaults by providing a function to `.extend()`.10611062```js1063import ky from 'ky';10641065const api = ky.create({prefix: 'https://example.com/api'});10661067const usersApi = api.extend((options) => ({prefix: `${options.prefix}/users`}));10681069const 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```10751076By 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.10771078When 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.10791080```js1081import ky, {replaceOption} from 'ky';10821083const api = ky.create({1084 hooks: {1085 beforeRequest: [addAuth, addTracking],1086 },1087});10881089// Appends as expected1090const extended = api.extend({hooks: {beforeRequest: [logRequest]}});1091// extended hooks.beforeRequest is [addAuth, addTracking, logRequest]10921093// Replaces instead of appending1094const replaced = api.extend({hooks: replaceOption({beforeRequest: [onlyThis]})});1095// replaced hooks.beforeRequest is [onlyThis]1096```10971098### ky.create(defaultOptions)10991100Create a new Ky instance with complete new defaults, without inheriting from any parent instance.11011102```js1103import ky from 'ky';11041105// On https://my-site.com11061107const api = ky.create({baseUrl: 'https://example.com/api/'});11081109const response = await api.get('users/123');1110//=> 'https://example.com/api/users/123'11111112const response = await api.get('status', {baseUrl: ''});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.11231124Note: 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.11251126A 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';11301131// Note that `response` will be `undefined` in case `ky.stop` is returned.1132const response = await ky.post('https://example.com', {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 }1143});11441145// Using `.text()` or other body methods is not supported, because there is no response to parse.1146```11471148### ky.retry(options?)11491150Force a retry from an `afterResponse` hook.11511152This 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`.11531154A 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.11551156#### options11571158Type: `object`11591160##### delay11611162Type: `number`11631164Custom delay in milliseconds before retrying. If not provided, uses the default retry delay calculation based on `retry.delay` configuration.11651166**Note:** Custom delays bypass jitter and `backoffLimit`. This is intentional, as custom delays often come from server responses (e.g., `Retry-After` headers) and should be respected exactly as specified.11671168Must be a non-negative number, `Infinity` included, or `undefined`; anything else makes the request throw a `TypeError` rather than collapsing to a 1ms retry.11691170##### code11711172Type: `string`11731174Error code for the retry.11751176This 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`.11771178```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 {1191 const data = await response.json();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.12061207This 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`.12081209**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.12101211> [!WARNING]1212> Custom retry requests are not sanitized. If you reuse headers across origins, remove any credentials you do not want forwarded.12131214#### Example12151216```js1217import ky, {isForceRetryError} from 'ky';12181219const api = ky.extend({1220 hooks: {1221 afterResponse: [1222 async ({request, response}) => {1223 // Retry based on response body content1224 if (response.status === 200) {1225 const data = await response.json();12261227 // 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');1289```12901291### KyError12921293Base class for all Ky-specific errors. `HTTPError`, `NetworkError`, `TimeoutError`, `ResponseSizeError`, and `ForceRetryError` extend this class.12941295You 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.12961297> [!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.12991300```js1301import ky, {isKyError} from 'ky';13021303try {1304 await ky('https://example.com').json();1305} catch (error) {1306 if (isKyError(error)) {1307 console.log('Ky error:', error.message);1308 }1309}1310```13111312### HTTPError13131314Exposed for `instanceof` checks. The error has a `response` property with the [`Response` object](https://developer.mozilla.org/en-US/docs/Web/API/Response), `request` property with the [`Request` object](https://developer.mozilla.org/en-US/docs/Web/API/Request), and `options` property with normalized options (either passed to `ky` when creating an instance with `ky.create()` or directly when performing the request).13151316It 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.13171318Be 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.13191320> [!NOTE]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.13221323```js1324import ky, {isHTTPError} from 'ky';13251326try {1327 await ky('https://example.com').json();1328} catch (error) {1329 if (isHTTPError(error)) {1330 console.log(error.data);1331 }1332}1333```13341335You can also use the `beforeError` hook:13361337```js1338import ky, {isHTTPError} from 'ky';13391340await ky('https://example.com', {1341 hooks: {1342 beforeError: [1343 ({error}) => {1344 if (isHTTPError(error) && error.data !== undefined) {1345 error.message = `${error.message}: ${JSON.stringify(error.data)}`;1346 }13471348 return error;1349 }1350 ]1351 }1352});1353```13541355⌨️ **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`.13561357### 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```13781379### 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).13821383```js1384import ky, {isTimeoutError} from 'ky';13851386try {1387 await ky('https://example.com').json();1388} catch (error) {1389 if (isTimeoutError(error)) {1390 console.log('Request timed out');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`);1407 }1408}1409```14101411### NetworkError14121413The error thrown when a network error occurs during the request (e.g., DNS failure, connection refused, offline). It has a `request` property with the [`Request` object](https://developer.mozilla.org/en-US/docs/Web/API/Request). The original error is available via the standard `cause` property.14141415Network 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.14161417> [!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}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.14361437Inside 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.14381439```js1440import ky, {replaceOption} from 'ky';14411442const api = ky.create({1443 headers: {authorization: 'Bearer token', 'x-custom': 'value'},1444});14451446// Replace all headers instead of merging1447const publicApi = api.extend({1448 headers: replaceOption({accept: 'application/json'}),1449});1450// Headers are now just {accept: 'application/json'}1451```14521453## Tips14541455### Sending form data14561457Sending 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.14581459```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```14691470If 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.14711472```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```14821483#### Modifying FormData in hooks14841485If you need to modify FormData in a `beforeRequest` hook (for example, to transform field names), delete the `Content-Type` header before creating a new `Request`:14861487```js1488import ky from 'ky';14891490const response = await ky.post(url, {1491 body: formData,1492 hooks: {1493 beforeRequest: [1494 ({request}) => {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```15111512### 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: {1521 'content-type': 'application/x-amz-json-1.1'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```15581559### 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```16471648### Streaming request bodies16491650You 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).16511652```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.16691670### 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```16841685### Pagination16861687Use [`fetch-extras`](https://github.com/sindresorhus/fetch-extras) with Ky for paginating API responses:16881689```js1690import ky from 'ky';1691import {paginate} from 'fetch-extras';16921693const url = 'https://api.github.com/repos/sindresorhus/ky/commits';16941695for await (const commit of paginate(url, {fetchFunction: ky})) {1696 console.log(commit.sha);1697}1698```16991700### Extending types17011702Ky's TypeScript types are intentionally defined as type aliases rather than interfaces to prevent global module augmentation, which can lead to type conflicts and unexpected behavior across your codebase. If you need to add custom properties to Ky's types like `KyResponse` or `HTTPError`, create local wrapper types instead:17031704```ts1705import ky, {HTTPError, isHTTPError} from 'ky';17061707interface CustomError extends HTTPError {1708 customProperty: unknown;1709}17101711// Use with type assertion1712let data: unknown;17131714const api = ky.extend({1715 hooks: {1716 beforeError: [1717 async ({error}) => {1718 if (isHTTPError(error)) {1719 (error as CustomError).customProperty = 'value';1720 data = (error as CustomError).customProperty;1721 }17221723 return error;1724 }1725 ]1726 }1727});1728```17291730This approach keeps your types scoped to where they're needed without polluting the global namespace.17311732## FAQ17331734#### How do I use this in Node.js?17351736Node.js supports `fetch` natively, so you can just use this package directly.17371738#### How do I use this with a web app (React, Vue.js, etc.) that uses server-side rendering (SSR)?17391740Node.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`:17411742```js1743const api = ky.create({1744 baseUrl: globalThis.window === undefined1745 ? (process.env.BASE_URL ?? 'http://localhost:3000')1746 : undefined,1747});1748```17491750<a name="baseurl-vs-prefix"></a>1751#### What's the difference between `baseUrl` and `prefix`?17521753**`baseUrl`** follows standard URL resolution rules — the same behavior as `new URL(input, baseUrl)`. A leading slash on the input means origin-root, overriding any path in the base URL.17541755**`prefix`** does plain string joining before URL resolution. The leading slash on the input is stripped, so it always appends to the prefix regardless.17561757Use `baseUrl` in almost all cases. Use `prefix` only when you want origin-relative inputs like `/users` to be treated as page-relative.17581759```js1760// On https://example.com17611762// baseUrl: standard URL resolution1763ky('users', {baseUrl: '/api/'});1764//=> https://example.com/api/users17651766ky('/users', {baseUrl: '/api/'});1767//=> https://example.com/users ← leading slash wins176817691770// prefix: always appends1771ky('users', {prefix: '/api'});1772//=> https://example.com/api/users17731774ky('/users', {prefix: '/api'});1775//=> https://example.com/api/users ← leading slash ignored1776```17771778#### How do I test a browser library that uses this?17791780Use a test runner that can run in the browser, like [Vitest](https://vitest.dev/guide/browser/) or [Playwright](https://playwright.dev).17811782#### 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```19111912#### 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```19261927#### How is it different from [`got`](https://github.com/sindresorhus/got)?19281929Got 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)?19321933Axios 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.19341935#### 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 support19461947Node.js 22 and later.19481949## 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)