Huge thanks to for sponsoring me!

Ky is a tiny and elegant HTTP client based on the browser Fetch API

Build Status codecov

Ky targets modern browsers and Deno. For older browsers, you will need to transpile and use a fetch polyfill. For Node.js, check out Got. For isomorphic needs (like SSR), check out ky-universal.

It's just a tiny file with no dependencies.

Benefits over plain fetch

  • Simpler API
  • Method shortcuts (
  • Treats non-2xx status codes as errors
  • Retries failed requests
  • JSON option
  • Timeout support
  • URL prefix option
  • Instances with custom defaults
  • Hooks


$ npm install ky


import ky from 'ky';

(async () => {
    const parsed = await'', {json: {foo: true}}).json();

    //=> `{data: '🦄'}`

With plain fetch, it would be:

(async () => {
    class HTTPError extends Error {}

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

    if (!response.ok) {
        throw new HTTPError('Fetch error:', response.statusText);

    const parsed = await response.json();

    //=> `{data: '🦄'}`

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

import ky from '';

In environments that do not support import, you can load ky in UMD format. For example, using require():

const ky = require('ky/umd').default;

With the UMD version, it's also easy to use ky without a bundler or module system.


ky(input, options?)

The input and options are the same as fetch, with some exceptions:

  • The credentials option is same-origin by default, which is the default in the spec too, but not all browsers have caught up yet.
  • Adds some more options. 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, proper Accept header will be set depending on body method used. Unlike the Body methods of window.Fetch; these will throw an HTTPError if the response status is not in the range 200...299.

ky.get(input, options?), options?)

ky.put(input, options?)

ky.patch(input, options?)

ky.head(input, options?)

ky.delete(input, options?)

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

When using a Request instance as input, any URL altering options (example: prefixUrl) will not work.


Type: object


Type: string
Default: get

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.


Type: object

Shortcut for sending JSON. Use this instead of the body option. Accepts a plain object which will be JSON.stringify()'d and the correct header will be set for you.


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

Search parameters to include in the request URL. Setting this will override all existing search parameters in the input URL.


Type: string | URL

When specified, prefixUrl will be prepended to input. The prefix can be any valid URL, either relative or absolute. A trailing slash / is optional, one will be added automatically, if needed, when joining prefixUrl and input. The input argument cannot start with a / when using this option.

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

import ky from 'ky';

// On

(async () => {
    await ky('unicorn', {prefixUrl: '/api'});
    //=> ''

    await ky('unicorn', {prefixUrl: ''});
    //=> ''

Type: object | number


  • limit: 2
  • methods: get put head delete options trace
  • statusCodes: 408 413 429 500 502 503 504
  • maxRetryAfter: undefined

An object representing limit, methods, statusCodes and maxRetryAfter fields for maximum retry count, allowed methods, allowed status codes and maximum Retry-After time.

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

If maxRetryAfter is set to undefined, it will use options.timeout. If Retry-After header is greater than maxRetryAfter, it will cancel the request.

Delays between retries is calculated with the function 0.3 * (2 ** (retry - 1)) * 1000, where retry is the attempt number (starts from 1).

import ky from 'ky';

(async () => {
    const parsed = await ky('', {
        retry: {
            limit: 10,
            methods: ['get'],
            statusCodes: [413]

Type: number | false
Default: 10000

Timeout in milliseconds for getting a response. Can not be greater than 2147483647. If set to false, there will be no timeout.


Type: object<string, Function[]>
Default: {beforeRequest: []}

Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially.


Type: Function[]
Default: []

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 normalized input and options as arguments. You could, for example, modify options.headers here.

Note that the argument order has changed in non-backward compatible way since #163.


Type: Function[]
Default: []

This hook enables you to read and optionally modify the response. The hook function receives normalized input, options, and a clone of the response as arguments. The return value of the hook function will be used by Ky as the response object if it's an instance of Response.

Note that the argument order has changed in non-backward compatible way since #163.

import ky from 'ky';

(async () => {
    await ky('', {
        hooks: {
            afterResponse: [
                (_input, _options, response) => {
                    // You could do something with the response, for example, logging.

                    // 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 (input, options, response) => {
                    if (response.status === 403) {
                        // Get a fresh token
                        const token = await ky('').text();

                        // Retry with the token
                        options.headers.set('Authorization', `token ${token}`);

                        return ky(input, options);

Type: boolean
Default: true

Throw a HTTPError for error responses (non-2xx status codes).

Setting this to false may be useful if you are checking for resource availability and are expecting error responses.


Type: Function

Download progress event handler.

The function receives a progress and chunk argument:

  • The progress object contains the following elements: percent, transferredBytes and totalBytes. If it's not possible to retrieve the body size, totalBytes will be 0.
  • The chunk argument is an instance of Uint8Array. It's empty for the first call.
import ky from 'ky';

(async () => {
    await ky('', {
        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`);


Create a new ky instance with some defaults overridden with your own.

In contrast to ky.create(), ky.extend() inherits defaults from its parent.


Create a new Ky instance with complete new defaults.

import ky from 'ky';

// On

const api = ky.create({prefixUrl: ''});

(async () => {
    await api.get('users/123');
    //=> ''

    await api.get('/status', {prefixUrl: ''});
    //=> ''


Type: object


Exposed for instanceof checks. The error has a response property with the Response object.


The error thrown when the request times out.


Sending Form Data

Sending form data in Ky is identical to fetch. Just pass a FormData instance to the body option. The Content-Type header will be automatically set to multipart/form-data. Setting it manually will result in an error.

import ky from 'ky';

(async () => {
    // `multipart/form-data`
    const formData = new FormData();
    formData.append('food', 'fries');
    formData.append('drink', 'icetea');

    await, {
        body: formData

If you want to send the data in application/x-www-form-urlencoded format, you will need to encode the data with URLSearchParams.

import ky from 'ky';

(async () => {
    // `application/x-www-form-urlencoded`
    const searchParams = new URLSearchParams();
    searchParams.set('food', 'fries');
    searchParams.set('drink', 'icetea');

    await, {
        body: searchParams


Fetch (and hence Ky) has built-in support for request cancellation through the AbortController API. Read more.


import ky from 'ky';

const controller = new AbortController();
const {signal} = controller;

setTimeout(() => {
}, 5000);

(async () => {
    try {
        console.log(await ky(url, {signal}).text());
    } catch (error) {
        if ( === 'AbortError') {
            console.log('Fetch aborted');
        } else {
            console.error('Fetch error:', error);


How do I use this in Node.js?

Check out ky-universal.

How do I use this with a web app (React, Vue.js, etc.) that uses server-side rendering (SSR)?

Check out ky-universal.

How do I test a browser library that uses this?

Either use a test runner that can run in the browser, like Mocha, or use AVA with ky-universal. Read more.

How do I use this without a bundler like Webpack?

Upload the index.js file in this repo somewhere, for example, to your website server, or use a CDN version. Then import the file.

<script type="module">
// Replace the version number with the latest version
import ky from '[email protected]/index.js';

(async () => {
    const parsed = await ky('').json();

    //=> 'delectus aut autem

Alternatively, you can use the umd.js file with a traditional <script> tag (without type="module"), in which case ky will be a global.

<!-- Replace the version number with the latest version -->
<script src="[email protected]/umd.js"></script>
(async () => {
    const ky = ky.default;

    const parsed = await ky('').json();

    //=> 'delectus aut autem

How is it different from got

See my answer here. Got is maintained by the same people as Ky.

How is it different from axios?

See my answer here.

How is it different from r2?

See my answer in #10.

What does ky mean?

It's just a random short npm package name I managed to get. It does, however, have a meaning in Japanese:

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.

Browser support

The latest version of Chrome, Firefox, and Safari.

Node.js support

Ky requires Node.js 10 or later, but it indicates Node.js 8 in package.json so you can use it with Node.js 8 by polyfilling the globals without having Yarn fail on install. However, you should just use ky-universal.


  • ky-universal - Use Ky in both Node.js and browsers
  • got - Simplified HTTP requests for Node.js