Why You Should Switch from axios to ky for Your Projects
HTTP requests are a common and essential task for any web developer. Whether you need to fetch data from an API, send data to a server, or perform any other kind of network operation, you need a reliable and easy-to-use tool for making HTTP requests.
There are many options available for JavaScript developers, but two of the most popular ones are axios and ky. Axios is a well-known and widely used library that provides a rich set of features and supports both browsers and Node.js. Ky is a newer and lighter library that focuses on modern browsers and offers a simpler and more elegant API.
In this blog post, I will compare ky and axios and show you why ky is a better choice for making HTTP requests in JavaScript. I will cover the following aspects:
- Size and performance
- Features and functionality
- Compatibility and support
- Developer experience and ease of use
Size and Performance
One of the main advantages of ky over axios is its size and performance. Ky is a lightweight library that has a smaller package size compared to axios. According to Bundlephobia, ky has a minified size of 9.5 KB and a gzipped size of 3.3 KB, while axios has a minified size of 30.5 KB and a gzipped size of 11.7 KB. This means that ky is faster to download and execute, which can improve the performance and user experience of your web applications.
Ky is also designed to be efficient and minimalistic, and it leverages the native Fetch API to perform HTTP requests. The Fetch API is a modern and standard way of making HTTP requests in browsers, and it offers better performance and compatibility than the older XMLHttpRequest object that axios uses under the hood. The Fetch API also supports features like streaming, caching, and service workers, which can enhance the functionality and performance of your web applications.
Features and Functionality
Both ky and axios provide similar core features for making HTTP requests, such as handling different request methods, headers, parameters, and responses. However, axios offers a wider range of features, such as automatic JSON parsing, request cancellation, interceptors, progress tracking, and support for both browsers and Node.js. Ky, on the other hand, focuses on a simpler and more modern API, and provides features like automatic retries, timeout handling, and browser-specific features.
Here are some examples of how you can use ky and axios to perform common HTTP tasks:
GET Request
To make a simple GET request, you can use the following code with ky:
// ky
const response = await ky.get('https://example.com/api/users');
const data = await response.json();
console.log(data);
And with axios:
// axios
const response = await axios.get('https://example.com/api/users');
const data = response.data;
console.log(data);
Notice that:
- Ky returns a Response object that conforms to the Fetch API specification, while axios returns a custom object that contains the data, status, headers, and other properties.
- Ky requires you to call the
response.json()
method to parse the response data to a JavaScript object similar to using fetch, while axios automatically parses the data for you. - Ky uses the
ky.get()
method to make a GET request, while axios uses theaxios.get()
method.
POST Request
To make a simple POST request, you can use the following code with ky:
// ky
const data = { name: 'Alice', age: 25 };
const response = await ky.post('https://example.com/api/users', { json: data });
const result = await response.json();
console.log(result);
And with axios:
// axios
const data = { name: 'Alice', age: 25 };
const response = await axios.post('https://example.com/api/users', data);
const result = response.data;
console.log(result);
Notice that:
- Ky accepts a
json
option to send the data as JSON, while axios automatically converts the data to JSON for you. - Ky and axios have the same syntax for making a POST request, except for the
json
option.
Customizing request
To add the access token for each request, you can use the following code with ky:
// ky
const api = ky.create({
prefixUrl: "https://example.com/api",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
// use a hook to add the authorization header before each request
hooks: {
beforeRequest: [
(request) => {
request.headers.set("Authorization", "Bearer token")
},
],
},
})
const response = await api.get("users")
const data = await response.json()
console.log(data)
And with axios:
// axios
const api = axios.create({
baseURL: "https://example.com/api",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
})
// use an interceptor to add the authorization header before each request
api.interceptors.request.use((config) => {
config.headers['Authorization'] = "Bearer token"
return config
})
const response = await api.get('users');
const data = response.data;
console.log(data);
Notice that:
- Ky uses the
hooks.beforeRequest
option to add a hook function that modifies the request headers, while axios uses theinterceptors.request
option to add an interceptor function that modifies the request config. - Ky uses the
request.headers.set()
method to set the header value, while axios uses theconfig.headers
object to set the header value. - Ky and axios have the same syntax for creating an instance, except for the
hooks
andinterceptors
options. - Ky supports multiple functions in the
hooks.beforeRequest
option, which will be executed in order before the request is sent. This allows you to perform different modifications or actions based on the request. For example, you can add a function to log the request details, and another function to add a custom header. You can also use async functions in the hooks, which will wait for the promise to resolve before proceeding to the next hook or the request. Axios also supports multiple functions in theinterceptors.request
option, but they are executed in reverse order, which can be confusing.
Compatibility and Support
Another important aspect to consider when choosing a library for making HTTP requests is its compatibility and support. Axios is compatible with both browsers and Node.js, making it suitable for universal JavaScript applications. It also has built-in support for XSRF protection, progress tracking, and easy integration with other JavaScript frameworks like React. Ky is also compatible with both browsers and Node.js, but its primary focus is on modern browsers. It provides better support for newer browser features like the Fetch API, AbortController, and URLSearchParams, and offers a more modern and elegant API design.
Axios is a more mature and widely used library, and it has a larger community and more extensive documentation. It also has more contributors and more frequent updates on GitHub. Ky, while having a smaller community, still provides comprehensive documentation with examples and guides to help developers get started. It also has a decent number of contributors and updates on GitHub.
Developer Experience and Ease of Use
The last aspect to consider when choosing a library for making HTTP requests is the developer experience and ease of use. Both ky and axios have good documentation and are relatively easy to use. However, ky has some advantages over axios in terms of simplicity, readability, and elegance. Ky has a more concise and intuitive API, and it uses the native Fetch API and promises to handle HTTP requests and responses. Ky also has a more consistent and predictable behavior, and it avoids some of the common pitfalls and quirks of axios, such as the need to stringify data, the difference between data
and response.data
, and the confusion between axios
and axios.request
.
Ky also has some nice features that axios does not have, such as automatic retries, timeout handling, and browser-specific features. These features can make your HTTP requests more robust, reliable, and convenient.
If you are interested in learning more about ky and axios, you can check out their full documentation here:
I hope this blog post has helped you understand the differences and advantages of ky over axios, and why you should use ky instead of axios for HTTP requests in JavaScript. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading! 😊