ky
- Version 1.13.0
- Published
- 237 kB
- No dependencies
- MIT license
Install
npm i kyyarn add kypnpm add kyOverview
Tiny and elegant HTTP client based on the Fetch API
Index
Variables
Functions
Classes
Interfaces
Type Aliases
Variables
variable ky
const ky: KyInstance;Functions
function isHTTPError
isHTTPError: <T = unknown>(error: unknown) => error is HTTPError<T>;Type guard to check if an error is an HTTPError.
Parameter error
The error to check
Returns
trueif the error is an HTTPError,falseotherwiseExample 1
import ky, {isHTTPError} from 'ky';try {const response = await ky.get('/api/data');} catch (error) {if (isHTTPError(error)) {console.log('HTTP error status:', error.response.status);}}
function isKyError
isKyError: (error: unknown) => error is HTTPError<unknown> | TimeoutError;Type guard to check if an error is a Ky error (HTTPError or TimeoutError).
Parameter error
The error to check
Returns
trueif the error is a Ky error,falseotherwiseExample 1
import ky, {isKyError} from 'ky';try {const response = await ky.get('/api/data');} catch (error) {if (isKyError(error)) {// Handle Ky-specific errorsconsole.log('Ky error occurred:', error.message);} else {// Handle other errorsconsole.log('Unknown error:', error);}}
function isTimeoutError
isTimeoutError: (error: unknown) => error is TimeoutError;Type guard to check if an error is a TimeoutError.
Parameter error
The error to check
Returns
trueif the error is a TimeoutError,falseotherwiseExample 1
import ky, {isTimeoutError} from 'ky';try {const response = await ky.get('/api/data', { timeout: 1000 });} catch (error) {if (isTimeoutError(error)) {console.log('Request timed out:', error.request.url);}}
Classes
class HTTPError
class HTTPError<T = unknown> extends Error {}constructor
constructor(response: Response, request: Request, options: NormalizedOptions);property options
options: NormalizedOptions;property request
request: KyRequest<unknown>;property response
response: KyResponse<T>;class TimeoutError
class TimeoutError extends Error {}constructor
constructor(request: Request);property request
request: KyRequest<unknown>;Interfaces
interface NormalizedOptions
interface NormalizedOptions extends RequestInit {}Normalized options passed to the
fetchcall and thebeforeRequesthooks.
property context
context: Record<string, unknown>;property credentials
credentials?: NonNullable<RequestInit['credentials']>;property method
method: NonNullable<RequestInit['method']>;property onDownloadProgress
onDownloadProgress: Options['onDownloadProgress'];property onUploadProgress
onUploadProgress: Options['onUploadProgress'];property prefixUrl
prefixUrl: string;property retry
retry: RetryOptions;interface Options
interface Options extends KyOptions, Omit<RequestInit, 'headers'> {}Options are the same as
window.fetch, except for the KyOptions
property headers
headers?: KyHeadersInit;HTTP headers used to make the request.
You can pass a
Headersinstance or a plain object.You can remove a header with
.extend()by passing the header with anundefinedvalue.Example 1
``` import ky from 'ky';
const url = 'https://sindresorhus.com';
const original = ky.create({ headers: { rainbow: 'rainbow', unicorn: 'unicorn' } });
const extended = original.extend({ headers: { rainbow: undefined } });
const response = await extended(url).json();
console.log('rainbow' in response); //=> false
console.log('unicorn' in response); //=> true ```
property method
method?: LiteralUnion<HttpMethod, string>;HTTP method used to make the request.
Internally, the standard methods (
GET,POST,PUT,PATCH,HEADandDELETE) are uppercased in order to avoid server errors due to case sensitivity.
Type Aliases
type AfterResponseHook
type AfterResponseHook = ( request: KyRequest, options: NormalizedOptions, response: KyResponse, state: AfterResponseState) => Response | void | Promise<Response | void>;type AfterResponseState
type AfterResponseState = { /** The number of retries attempted. `0` for the initial request, increments with each retry.
This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., showing a notification only on the final retry). */ retryCount: number;};type BeforeErrorHook
type BeforeErrorHook = ( error: HTTPError, state: BeforeErrorState) => HTTPError | Promise<HTTPError>;type BeforeErrorState
type BeforeErrorState = { /** The number of retries attempted. `0` for the initial request, 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). */ retryCount: number;};type BeforeRequestHook
type BeforeRequestHook = ( request: KyRequest, options: NormalizedOptions, state: BeforeRequestState) => Request | Response | void | Promise<Request | Response | void>;type BeforeRequestState
type BeforeRequestState = { /** The number of retries attempted. `0` for the initial request, increments with each retry.
This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., avoiding overwriting headers set in `beforeRetry`). */ retryCount: number;};type BeforeRetryHook
type BeforeRetryHook = ( options: BeforeRetryState) => | Request | Response | typeof stop | void | Promise<Request | Response | typeof stop | void>;type BeforeRetryState
type BeforeRetryState = { request: KyRequest; options: NormalizedOptions; error: Error; /** The number of retries attempted. Always `>= 1` since this hook is only called during retries, not on the initial request. */ retryCount: number;};type Hooks
type Hooks = { /** This 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 the normalized request, options, and a state object. You could, for example, modify `request.headers` here.
The `state.retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., avoiding overwriting headers set in `beforeRetry`).
A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) can be returned from this hook to completely avoid making a HTTP request. This can be used to mock a request, check an internal cache, etc. An **important** consideration when returning a `Response` from this hook is that all the following hooks will be skipped, so **ensure you only return a `Response` from the last hook**.
@example ``` import ky from 'ky';
const response = await ky('https://example.com', { hooks: { beforeRequest: [ (request, options, {retryCount}) => { // Only set default auth header on initial request, not on retries // (retries may have refreshed token set by beforeRetry) if (retryCount === 0) { request.headers.set('Authorization', 'token initial-token'); } } ] } }); ```
@default [] */ beforeRequest?: BeforeRequestHook[]; /** This 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 an object with the normalized request and options, an error instance, and the retry count. You could, for example, modify `request.headers` here.
The 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. **Note:** Returning a request or response skips remaining `beforeRetry` hooks.
If the request received a response, the error will be of type `HTTPError` and the `Response` object will be available at `error.response`. 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 not be an instance of `HTTPError`.
You 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`](#ky.stop) symbol to do the same thing but without propagating an error (this has some limitations, see `ky.stop` docs for details).
**Modifying headers:**
@example ``` import ky from 'ky';
const response = await ky('https://example.com', { hooks: { beforeRetry: [ async ({request, options, error, retryCount}) => { const token = await ky('https://example.com/refresh-token'); request.headers.set('Authorization', `token ${token}`); } ] } }); ```
**Modifying the request URL:**
@example ``` import ky from 'ky';
const response = await ky('https://example.com/api', { hooks: { beforeRetry: [ async ({request, error}) => { // Add query parameters based on error response if (error.response) { const body = await error.response.json(); const url = new URL(request.url); url.searchParams.set('processId', body.processId); return new Request(url, request); } } ] } }); ```
**Returning a cached response:**
@example ``` import ky from 'ky';
const response = await ky('https://example.com/api', { hooks: { beforeRetry: [ ({error, retryCount}) => { // Use cached response instead of retrying if (retryCount > 1 && cachedResponse) { return cachedResponse; } } ] } }); ```
@default [] */ beforeRetry?: BeforeRetryHook[]; /** This hook enables you to read and optionally modify the response. The hook function receives normalized request, options, a clone of the response, and a state object. 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).
@default []
@example ``` import ky from 'ky';
const response = await ky('https://example.com', { hooks: { afterResponse: [ (_request, _options, response) => { // You could do something with the response, for example, logging. log(response);
// Or return a `Response` instance to overwrite the response. return new Response('A different response', {status: 200}); },
// Or retry with a fresh token on a 403 error async (request, options, response) => { if (response.status === 403) { // Get a fresh token const token = await ky('https://example.com/token').text();
// Retry with the token options.headers.set('Authorization', `token ${token}`);
return ky(request, options); } },
// Or show a notification only on the last retry for 5xx errors (request, options, response, {retryCount}) => { if (response.status >= 500 && response.status <= 599) { if (retryCount === options.retry.limit) { showNotification('Request failed after all retries'); } } } ] } }); ``` */ afterResponse?: AfterResponseHook[]; /** This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives a `HTTPError` and a state object as arguments and should return an instance of `HTTPError`.
@default []
@example ``` import ky from 'ky';
await ky('https://example.com', { hooks: { beforeError: [ async error => { const {response} = error; if (response) { const body = await response.json(); error.name = 'GitHubError'; error.message = `${body.message} (${response.status})`; }
return error; },
// Or show different message based on retry count (error, {retryCount}) => { if (retryCount === error.options.retry.limit) { error.message = `${error.message} (failed after ${retryCount} retries)`; }
return error; } ] } }); ``` */ beforeError?: BeforeErrorHook[];};type Input
type Input = string | URL | Request;type KyInstance
type KyInstance = { /** Fetch the given `url`.
@param url - `Request` object, `URL` object, or URL string. @returns A promise with `Body` method added.
@example ``` import ky from 'ky';
const json = await ky('https://example.com', {json: {foo: true}}).json();
console.log(json); //=> `{data: '🦄'}` ``` */ <T>(url: Input, options?: Options): ResponsePromise<T>; /** Fetch the given `url` using the option `{method: 'get'}`.
@param url - `Request` object, `URL` object, or URL string. @returns A promise with `Body` methods added. */ get: <T>(url: Input, options?: Options) => ResponsePromise<T>; /** Fetch the given `url` using the option `{method: 'post'}`.
@param url - `Request` object, `URL` object, or URL string. @returns A promise with `Body` methods added. */ post: <T>(url: Input, options?: Options) => ResponsePromise<T>; /** Fetch the given `url` using the option `{method: 'put'}`.
@param url - `Request` object, `URL` object, or URL string. @returns A promise with `Body` methods added. */ put: <T>(url: Input, options?: Options) => ResponsePromise<T>; /** Fetch the given `url` using the option `{method: 'delete'}`.
@param url - `Request` object, `URL` object, or URL string. @returns A promise with `Body` methods added. */ delete: <T>(url: Input, options?: Options) => ResponsePromise<T>; /** Fetch the given `url` using the option `{method: 'patch'}`.
@param url - `Request` object, `URL` object, or URL string. @returns A promise with `Body` methods added. */ patch: <T>(url: Input, options?: Options) => ResponsePromise<T>; /** Fetch the given `url` using the option `{method: 'head'}`.
@param url - `Request` object, `URL` object, or URL string. @returns A promise with `Body` methods added. */ head: (url: Input, options?: Options) => ResponsePromise; /** Create a new Ky instance with complete new defaults.
@returns A new Ky instance. */ create: (defaultOptions?: Options) => KyInstance; /** Create a new Ky instance with some defaults overridden with your own.
In contrast to `ky.create()`, `ky.extend()` inherits defaults from its parent.
You can also refer to parent defaults by providing a function to `.extend()`.
@example ``` import ky from 'ky';
const api = ky.create({prefixUrl: 'https://example.com/api'});
const usersApi = api.extend((options) => ({prefixUrl: `${options.prefixUrl}/users`}));
const response = await usersApi.get('123'); //=> 'https://example.com/api/users/123'
const response = await api.get('version'); //=> 'https://example.com/api/version' ```
@returns A new Ky instance. */ extend: ( defaultOptions: Options | ((parentOptions: Options) => Options) ) => KyInstance; /** A `Symbol` that can be returned by a `beforeRetry` hook to stop the retry. This will also short circuit the remaining `beforeRetry` hooks.
Note: 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. 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.
A 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.
@example ``` import ky from 'ky';
const options = { hooks: { beforeRetry: [ async ({request, options, error, retryCount}) => { const shouldStopRetry = await ky('https://example.com/api'); if (shouldStopRetry) { return ky.stop; } } ] } };
// Note that response will be `undefined` in case `ky.stop` is returned. const response = await ky.post('https://example.com', options);
// Using `.text()` or other body methods is not supported. const text = await ky('https://example.com', options).text(); ``` */ readonly stop: typeof stop;};type KyRequest
type KyRequest<T = unknown> = { json: <J = T>() => Promise<J>;} & Request;type KyResponse
type KyResponse<T = unknown> = { json: <J = T>() => Promise<J>;} & Response;type Progress
type Progress = { percent: number; transferredBytes: number; /** Note: If it's not possible to retrieve the body size, it will be `0`. */ totalBytes: number;};type ResponsePromise
type ResponsePromise<T = unknown> = { arrayBuffer: () => Promise<ArrayBuffer>; blob: () => Promise<Blob>; formData: () => Promise<FormData>; /** Get the response body as raw bytes.
Note: This shortcut is only available when the runtime supports `Response.prototype.bytes()`. */ bytes: () => Promise<Uint8Array>; /** Get the response body as JSON.
@example ``` import ky from 'ky';
const json = await ky(…).json(); ```
@example ``` import ky from 'ky';
interface Result { value: number; }
const result1 = await ky(…).json<Result>(); // or const result2 = await ky<Result>(…).json(); ``` */ json: <J = T>() => Promise<J>; text: () => Promise<string>;} & Promise<KyResponse<T>>;type RetryOptions
type RetryOptions = { /** The number of times to retry failed requests.
@default 2 */ limit?: number; /** The HTTP methods allowed to retry.
@default ['get', 'put', 'head', 'delete', 'options', 'trace'] */ methods?: string[]; /** The HTTP status codes allowed to retry.
@default [408, 413, 429, 500, 502, 503, 504] */ statusCodes?: number[]; /** The HTTP status codes allowed to retry with a `Retry-After` header.
@default [413, 429, 503] */ afterStatusCodes?: number[]; /** If the `Retry-After` header is greater than `maxRetryAfter`, the request will be canceled.
@default Infinity */ maxRetryAfter?: number; /** The upper limit of the delay per retry in milliseconds. To clamp the delay, set `backoffLimit` to 1000, for example.
By default, the delay is calculated in the following way:
``` 0.3 * (2 ** (attemptCount - 1)) * 1000 ```
The delay increases exponentially.
@default Infinity */ backoffLimit?: number; /** A function to calculate the delay between retries given `attemptCount` (starts from 1).
@default attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000 */ delay?: (attemptCount: number) => number; /** Add 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.
@default undefined (no jitter)
@example ``` import ky from 'ky';
const json = await ky('https://example.com', { retry: { limit: 5,
// Full jitter (randomizes delay between 0 and computed value) jitter: true
// Percentage jitter (80-120% of delay) // jitter: delay => delay * (0.8 + Math.random() * 0.4)
// Absolute jitter (±100ms) // jitter: delay => delay + (Math.random() * 200 - 100) } }).json(); ``` */ jitter?: boolean | ((delay: number) => number) | undefined; /** Whether to retry when the request times out.
@default false
@example ``` import ky from 'ky';
const json = await ky('https://example.com', { retry: { limit: 3, retryOnTimeout: true } }).json(); ``` */ retryOnTimeout?: boolean; /** A function to determine whether a retry should be attempted.
This function takes precedence over all other retry checks and is called first, before any other retry validation.
**Note:** This is different from the `beforeRetry` hook: - `shouldRetry`: Controls WHETHER to retry (called before the retry decision is made) - `beforeRetry`: Called AFTER retry is confirmed, allowing you to modify the request
Should return: - `true` to force a retry (bypasses `retryOnTimeout`, status code checks, and other validations) - `false` to prevent a retry (no retry will occur) - `undefined` to use the default retry logic (`retryOnTimeout`, status codes, etc.)
@example ``` import ky, {HTTPError} from 'ky';
const json = await ky('https://example.com', { retry: { limit: 3, shouldRetry: ({error, retryCount}) => { // Retry on specific business logic errors from API if (error instanceof HTTPError) { const status = error.response.status;
// Retry on 429 (rate limit) but only for first 2 attempts if (status === 429 && retryCount <= 2) { return true; }
// Don't retry on 4xx errors except rate limits if (status >= 400 && status < 500) { return false; } }
// Use default retry logic for other errors return undefined; } } }).json(); ``` */ shouldRetry?: ( state: ShouldRetryState ) => boolean | undefined | Promise<boolean | undefined>;};type SearchParamsOption
type SearchParamsOption = | SearchParamsInit | Record<string, string | number | boolean | undefined> | Array<Array<string | number | boolean>>;type ShouldRetryState
type ShouldRetryState = { /** The error that caused the request to fail. */ error: Error; /** The number of retries attempted. Starts at 1 for the first retry. */ retryCount: number;};Package Files (11)
- distribution/errors/HTTPError.d.ts
- distribution/errors/TimeoutError.d.ts
- distribution/index.d.ts
- distribution/types/ResponsePromise.d.ts
- distribution/types/hooks.d.ts
- distribution/types/ky.d.ts
- distribution/types/options.d.ts
- distribution/types/request.d.ts
- distribution/types/response.d.ts
- distribution/types/retry.d.ts
- distribution/utils/type-guards.d.ts
Dependencies (0)
No dependencies.
Dev Dependencies (20)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/ky.
- Markdown[](https://www.jsdocs.io/package/ky)
- HTML<a href="https://www.jsdocs.io/package/ky"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 4034 ms. - Missing or incorrect documentation? Open an issue for this package.
