Skip to content
D
Documentation

Instances and defaults

concept
1 min readUpdated

A Ky instance carries request defaults for a particular use case. Use ky's create() method to start an instance with its own defaults, and extend() to derive an instance that inherits and modifies its parent's defaults. An instance has the request methods and factory methods described by KyInstance.

How defaults flow

Each request combines the instance's defaults with options supplied for that request. Creating from an instance starts fresh; extending it starts from its current defaults.

mermaid
flowchart TD
    K["ky"] -->|"create(defaults)"| A["Instance A"]
    A -->|request options| R["Request"]
    A -->|"extend(overrides)"| B["Instance B: inherited and modified defaults"]
    B -->|request options| S["Request"]
    A -->|"create(newDefaults)"| C["Instance C: new defaults only"]

Extend from parent defaults

An extend() callback can compute new defaults from the parent defaults. This is useful when a child scope builds on a configured prefix:

ts
import ky from 'ky';

async function main() {
const api = ky.create({prefix: 'https://api.example.com/api'});
const usersApi = api.extend(parentOptions => ({
	prefix: `${parentOptions.prefix}/users`,
}));

await usersApi.get('123');
}

void main();

The request uses the https://api.example.com/api/users/123 URL. The callback returns overrides; it does not mutate the parent instance.

Which factory to use

CallDefaults usedChoose it when
ky.create(defaultOptions)Only the options passed to this callYou need a separate client that does not inherit another instance's defaults.
instance.extend(defaultOptions)Parent defaults merged with the new optionsYou need a specialized client based on an existing instance.
instance.extend(parentOptions => overrides)Parent defaults are available to calculate the returned overridesThe child defaults depend on the parent's configuration.
replaceOption(value) inside extend()Replaces that merged option valueYou need to discard the parent's value for that option.

Use baseUrl when relative request inputs should resolve against a base URL. It does not change absolute inputs. prefix is applied to string inputs before baseUrl resolution; the Options reference describes both URL options and the rest of the request defaults.

Was this page helpful?