Ky is a tiny and elegant HTTP client built on the Fetch API. At just ~3KB, it provides retry logic, timeout handling, hooks, and JSON shortcuts that the native fetch lacks.
Installation
npm install ky
Basic Usage
import ky from "ky";
// Simple GET with automatic JSON parsing
const data = await ky.get("https://api.github.com/users/sindresorhus").json();
console.log(data.name); // Sindre Sorhus
// POST with JSON body
const response = await ky.post("https://httpbin.org/post", {
json: { name: "Ky", type: "http-client" }
}).json();
Retry and Timeout
// Auto-retry on network errors and 5xx responses
const api = ky.create({
prefixUrl: "https://api.example.com",
retry: { limit: 3, methods: ["get"], statusCodes: [408, 502, 503, 504] },
timeout: 10000,
headers: { "Authorization": "Bearer token" }
});
const users = await api.get("users").json();
Hooks — Intercept Requests and Responses
const api = ky.create({
hooks: {
beforeRequest: [
(request) => {
request.headers.set("X-Request-ID", crypto.randomUUID());
}
],
afterResponse: [
async (request, options, response) => {
if (response.status === 401) {
const token = await refreshToken();
request.headers.set("Authorization", `Bearer ${token}`);
return ky(request);
}
}
]
}
});
Search Params
const data = await ky.get("https://api.example.com/search", {
searchParams: { q: "web scraping", page: 1, limit: 20 }
}).json();
Why Ky Over Fetch?
- Automatic retries on network errors
- Timeout support (fetch has none by default)
- JSON shortcuts (.json() method, json option for body)
- Hooks for request/response interception
- Tiny bundle — ~3KB gzipped
Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.
Top comments (0)