Skip to content

Interface: KyRequestOptions

Options are the same as window.fetch, except for the KyOptions

Extends

  • KyOptions.Omit<RequestInit, "headers">

Properties

PropertyTypeDescriptionOverridesInherited from
body?BodyInit | nullA BodyInit object or null to set request's body.-Omit.body
cache?RequestCacheA string indicating how the request will interact with the browser's cache to set request's cache.-Omit.cache
context?Record<string, unknown>User-defined data passed to hooks. This 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. Use cases: - Pass authentication tokens or API keys to hooks - Attach request metadata for logging or debugging - Implement conditional logic in hooks based on the request context - Pass serverless environment bindings (e.g., Cloudflare Workers) Note: Context is shallow merged. Top-level properties are merged, but nested objects are replaced. Only enumerable properties are copied. Example import ky from 'ky'; // Pass data to hooks const api = ky.create({ hooks: { beforeRequest: [ (request, options) => { const {token} = options.context; if (token) { request.headers.set('Authorization', Bearer ${token}); } } ] } }); await api('https://example.com', { context: { token: 'secret123' } }).json(); // Shallow merge: only top-level properties are merged const instance = ky.create({ context: { a: 1, b: { nested: true } } }); const extended = instance.extend({ context: { b: { updated: true }, c: 3 } }); // Result: {a: 1, b: {updated: true}, c: 3} // Note: The original b.nested is gone (shallow merge)-KyOptions.context
credentials?RequestCredentialsA string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials.-Omit.credentials
fetch?(input: Input, init?: RequestInit) => Promise<Response>User-defined fetch function. Has to be fully compatible with the Fetch API standard. Use-cases: 1. Use custom fetch implementations like isomorphic-unfetch. 2. Use the fetch wrapper function provided by some frameworks that use server-side rendering (SSR). Default fetch Example import ky from 'ky'; import fetch from 'isomorphic-unfetch'; const json = await ky('https://example.com', {fetch}).json();-KyOptions.fetch
headers?KyHeadersInitHTTP headers used to make the request. You can pass a Headers instance or a plain object. You can remove a header with .extend() by passing the header with an undefined value. Example 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--
hooks?HooksHooks allow modifications during the request lifecycle. Hook functions may be async and are run serially.-KyOptions.hooks
integrity?stringA cryptographic hash of the resource to be fetched by request. Sets request's integrity.-Omit.integrity
json?unknownShortcut for sending JSON. Use this instead of the body option. Accepts any plain object or value, which will be JSON.stringify()'d and sent in the body with the correct header set.-KyOptions.json
keepalive?booleanA boolean to set request's keepalive.-Omit.keepalive
method?LiteralUnion<HttpMethod, string>HTTP method used to make the request. Internally, the standard methods (GET, POST, PUT, PATCH, HEAD and DELETE) are uppercased in order to avoid server errors due to case sensitivity.Omit.method-
mode?RequestModeA string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode.-Omit.mode
onDownloadProgress?(progress: Progress, chunk: Uint8Array) => voidDownload progress event handler. Example import ky from 'ky'; const response = await ky('https://example.com', { onDownloadProgress: (progress, chunk) => { // Example output: // 0% - 0 of 1271 bytes//100% - 1271 of 1271 bytes console.log(${progress.percent * 100}% - ${progress.transferredBytes} of ${progress.totalBytes} bytes); } });-KyOptions.onDownloadProgress
onUploadProgress?(progress: Progress, chunk: Uint8Array) => voidUpload progress event handler. Example import ky from 'ky'; const response = await ky.post('https://example.com/upload', { body: largeFile, onUploadProgress: (progress, chunk) => { // Example output: // 0% - 0 of 1271 bytes//100% - 1271 of 1271 bytes console.log(${progress.percent * 100}% - ${progress.transferredBytes} of ${progress.totalBytes} bytes); } });-KyOptions.onUploadProgress
parseJson?(text: string) => unknownUser-defined JSON-parsing function. Use-cases: 1. Parse JSON via the bourne package to protect from prototype pollution. 2. Parse JSON with reviver option of JSON.parse(). Default JSON.parse() Example import ky from 'ky'; import bourne from '@hapijs/bourne'; const json = await ky('https://example.com', { parseJson: text => bourne(text) }).json();-KyOptions.parseJson
prefixUrl?string | URLA prefix to prepend to the input URL when making the request. It can be any valid 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. The input argument cannot start with a slash / when using this option. Useful when used with ky.extend() to create niche-specific Ky-instances. Notes: - After prefixUrl and input are joined, the result is resolved against the base URL of the page (if any). - Leading slashes in input are disallowed when using this option to enforce consistency and avoid confusion about how the input URL is handled, given that input will not follow the normal URL resolution rules when prefixUrl is being used, which changes the meaning of a leading slash. Example import ky from 'ky'; // On https://example.com const response = await ky('unicorn', {prefixUrl: '/api'}); //=> 'https://example.com/api/unicorn' const response = await ky('unicorn', {prefixUrl: 'https://cats.com'}); //=> 'https://cats.com/unicorn'-KyOptions.prefixUrl
priority?RequestPriority--Omit.priority
redirect?RequestRedirectA string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect.-Omit.redirect
referrer?stringA string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer.-Omit.referrer
referrerPolicy?ReferrerPolicyA referrer policy to set request's referrerPolicy.-Omit.referrerPolicy
retry?number | RetryOptionsAn object representing limit, methods, statusCodes, afterStatusCodes, and maxRetryAfter fields for maximum retry count, allowed methods, allowed status codes, status codes allowed to use the Retry-After time, and maximum Retry-After time. If retry is a number, it will be used as limit and other defaults will remain in place. If the response provides an HTTP status contained in afterStatusCodes, Ky will wait until the date or timeout given in the Retry-After header has passed to retry the request. If Retry-After is missing, the non-standard RateLimit-Reset header is used in its place as a fallback. If the provided status code is not in the list, the Retry-After header will be ignored. If maxRetryAfter is set to undefined, it will use options.timeout. If Retry-After header is greater than maxRetryAfter, it will cancel the request. By default, delays between retries are calculated with the function 0.3 * (2 ** (attemptCount - 1)) * 1000, where attemptCount is the attempt number (starts from 1), however this can be changed by passing a delay function. Retries are not triggered following a timeout. Example import ky from 'ky'; const json = await ky('https://example.com', { retry: { limit: 10, methods: ['get'], statusCodes: [413] } }).json();-KyOptions.retry
searchParams?SearchParamsOptionSearch parameters to include in the request URL. Setting this will override all existing search parameters in the input URL. Accepts any value supported by URLSearchParams(). When passing an object, undefined values are automatically filtered out, while null values are preserved and converted to the string 'null'.-KyOptions.searchParams
signal?AbortSignal | nullAn AbortSignal to set request's signal.-Omit.signal
stringifyJson?(data: unknown) => stringUser-defined JSON-stringifying function. Use-cases: 1. Stringify JSON with a custom replacer function. Default JSON.stringify() Example import ky from 'ky'; import {DateTime} from 'luxon'; const json = await ky('https://example.com', { stringifyJson: data => JSON.stringify(data, (key, value) => { if (key.endsWith('_at')) { return DateTime.fromISO(value).toSeconds(); } return value; }) }).json();-KyOptions.stringifyJson
throwHttpErrors?boolean | (status: number) => booleanThrow 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 option to 'manual'. Setting this to false may be useful if you are checking for resource availability and are expecting error responses. You 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. Note: If false, error responses are considered successful and the request will not be retried. Default true-KyOptions.throwHttpErrors
timeout?number | falseTimeout in milliseconds for getting a response, including any retries. Can not be greater than 2147483647. If set to false, there will be no timeout. Default 10000-KyOptions.timeout
window?nullCan only be null. Used to disassociate request from any Window.-Omit.window