Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
K

ky

> 包管理
Open source

🌳 Tiny & elegant JavaScript HTTP client based on the Fetch API

17.0K stars0 likes3 views
WebsiteGitHub

About

🌳 Tiny & elegant JavaScript HTTP client based on the Fetch API





Ky is a tiny and elegant HTTP client based on the Fetch API Ky targets modern browsers, Node.js, Bun, and Deno.

It's just a tiny package with no dependencies.

Benefits over plain fetch

  • Simpler API
  • Method shortcuts (ky.post())
  • Treats non-2xx status codes as errors (after redirects)
  • Retries failed requests
  • JSON option
  • Timeout support
  • Upload and download progress
  • Base URL option
  • Instances with custom defaults
  • Hooks
  • Response validation with Standard Schema (Zod, Valibot, etc.)
  • TypeScript niceties (e.g., .json() supports generics and defaults to unknown, not any)

Install

bash
npm install ky

[!NOTE] This readme is for the next version of Ky. For the current version, click here.

CDN
  • jsdelivr
  • unpkg
  • esm.sh

Usage

javascript
import ky from 'ky';

const json = await ky.post('https://example.com', {json: {foo: true}}).json();

console.log(json);
//=> {data: '🦄'}

With plain fetch, it would be:

javascript
class HTTPError extends Error {}

const response = await fetch('https://example.com', {
	method: 'POST',
	body: JSON.stringify({foo: true}),
	headers: {
		'content-type': 'application/json'
	}
});

if (!response.ok) {
	throw new HTTPError(`Fetch error: ${response.statusText}`);
}

const json = await response.json();

console.log(json);
//=> {data: '🦄'}

If you are using Deno, import Ky from a URL. For example, using a CDN:

javascript
import ky from 'https://esm.sh/ky';

API

ky(input, options?)

The input and options are the same as fetch, with additional options available (see below).

Returns a Response object with Body methods 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.

Available body shortcuts: .json(), .text(), .formData(), .arrayBuffer(), .blob(), and .bytes(). The .bytes() shortcut is only present when the runtime supports Response.prototype.bytes().

javascript
import ky from 'ky';

const user = await ky('/api/user').json();

console.log(user);

⌨️ TypeScript: Accepts an optional type parameter, which defaults to unknown, and is passed through to the return type of .json().

typescript
import ky from 'ky';

// user1 is unknown
const user1 = await ky('/api/users/1').json();
// user2 is a User
const user2 = await ky<User>('/api/users/2').json();
// user3 is a User
const user3 = await ky('/api/users/3').json<User>();

console.log([user1, user2, user3]);

You 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.

typescript
import ky, {SchemaValidationError} from 'ky';
import {z} from 'zod';

const userSchema = z.object({name: z.string()});

try {
	const user = await ky('/api/user').json(userSchema);
	console.log(user.name);
} catch (error) {
	if (error instanceof SchemaValidationError) {
		console.error(error.issues);
	}
}
typescript
// Get raw bytes (when supported by the runtime)
const bytes = await ky('/api/file').bytes();
console.log(bytes instanceof Uint8Array);

ky.get(input, options?)

ky.post(input, options?)

ky.put(input, options?)

ky.patch(input, options?)

ky.head(input, options?)

ky.delete(input, options?)

ky.query(input, options?)

Sets options.method to the method name and makes a request.

⌨️ TypeScript: Accepts an optional type parameter for use with JSON responses (see ky()).

input

Type: string | URL | Request

Same as fetch input.

When using a Request instance as input, any URL altering options (such as baseUrl) will be ignored.

options

Type: object

Same as fetch options, plus the following additional options:

method

Type: string
Default: 'get'

HTTP method used to make the request.

Internally, the standard methods (GET, POST, PUT, PATCH, HEAD, DELETE, and QUERY) are uppercased in order to avoid server errors due to case sensitivity.

json

Type: object and any other value accepted by JSON.stringify()

Shortcut 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.

The 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.

searchParams

Type: string | object<string, string | number | boolean | undefined> | Array<Array<string | number | boolean>> | URLSearchParams
Default: ''

Search parameters to include in the request URL. Setting this will merge with any existing search parameters in the input URL.

Accepts any value supported by URLSearchParams().

When passing an object, setting a value to undefined deletes the parameter, while null values are preserved and converted to the string 'null'.

When input is a Request with a body, the body is sent as a stream, which requires request stream support and HTTP/2 for HTTPS connections (in Chromium-based browsers). In environments without request stream support, when keepalive is true, or when the effective mode is 'no-cors', the inherited body is dropped. A compatible body passed explicitly with the body option is still used.

baseUrl

Type: string | URL

A base URL to resolve 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.

Useful when used with ky.extend() to create niche-specific Ky instances.

If the baseUrl itself is relative, it will be resolved against the environment's base URL, such as document.baseURI in browsers or location.href in Deno (see the --location flag).

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.

javascript
import ky from 'ky';

// On https://example.com

const response = await ky('users', {baseUrl: '/api/'});
//=> 'https://example.com/api/users'

const response = await ky('/users', {baseUrl: '/api/'});
//=> 'https://example.com/users'

See FAQ: baseUrl vs prefix

prefix

Type: string | URL

A 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.

Useful when used with ky.extend() to create niche-specific Ky instances.

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.

See FAQ: baseUrl vs prefix

javascript
import ky from 'ky';

// On https://example.com

const response = await ky('users', {prefix: '/api/'});
//=> 'https://example.com/api/users'

const response = await ky('/users', {prefix: '/api/'});
//=> 'https://example.com/api/users'

Notes:

  • 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.
  • After prefix and input are joined, the result is resolved against the baseUrl option, if present.
retry

Type: object | number
Default:

  • limit: 2
  • methods: get put head delete options trace query
  • statusCodes: 408 413 429 500 502 503 504
  • afterStatusCodes: 413, 429, 503
  • maxRetryAfter: Infinity
  • backoffLimit: Infinity
  • delay: attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000
  • jitter: undefined
  • retryOnTimeout: false
  • shouldRetry: undefined

Controls retry behavior. Each field is documented individually below.

If retry is a number, it will be used as limit and other defaults will remain in place.

retry.limit, including numeric shorthand, must be a finite, non-negative integer.

Network 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.

413 Payload Too Large is only retried when the response includes a retry timing header.

When the response status is contained in both statusCodes and afterStatusCodes, Ky uses retry timing headers to choose the retry delay. Retry-After may provide a delay in seconds

Issues· 2 open

View all issuesOpen on GitHub
  • #886

    CI runs the browser tests and Playwright install on all three Node versions

    Updated Sep 30, 2026
  • #885

    Feature: Support Modifying Options on Retry

    Updated Sep 14, 2026

> Tags

TypeScriptfetchhttp-clienthttp-requestjavascript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 1, 2026
Category包管理
PricingOpen source

> Related tools

N
npm
Node.js 默认包管理器
P
pnpm
高效节省磁盘的 Node 包管理器
I
is-gif
Check if a Buffer/Uint8Array is a GIF image