createKyExecutor(instanceOrFactory, options?) — @routar/ky
Accepts a KyInstance (CSR) or a factory function that returns one (SSR).
import ky from 'ky'
import { createKyExecutor } from '@routar/ky'
// CSR — shared instance
const executor = createKyExecutor(ky.create({ prefixUrl: 'https://api.example.com' }))Instance vs. factory
// CSR — pass the instance directly
const executor = createKyExecutor(ky.create({ prefixUrl: BASE_URL }))
// SSR — factory, called per-request for fresh headers
const executor = createKyExecutor(async () => {
const token = await getServerToken()
return ky.create({
prefixUrl: BASE_URL,
headers: { Authorization: `Bearer ${token}` },
})
})The factory form is called on every request, making it safe for per-request auth headers in SSR environments.
Options
| Option | Type | Description |
|---|---|---|
middlewares | ExecutorMiddleware[] | Middleware chain for this executor |
Errors
ky errors propagate as HTTPError. All ky-specific fields are preserved:
import { HTTPError } from 'ky'
try {
await todoApi.getDetail({ path: { id: 999 } })
} catch (err) {
if (err instanceof HTTPError) {
console.log(err.response.status) // 404
console.log(await err.response.json()) // server error body
}
}Instance detection
createKyExecutor distinguishes a KyInstance from a factory function via duck-typing: it checks for the extend method. KyInstance objects always have .extend(); plain factory functions do not.
prefixUrl requirement
The KyInstance must have prefixUrl set. routar route paths (e.g. /todos) have their leading / stripped before being passed to ky, which requires relative paths when prefixUrl is configured.
Last updated on