Hello dear dev!
Ky has been around for several years now, presenting itself as a lightweight, modern alternative to browser fetching. Built on top of the Fetch API, it offers handy features such as hooks and the much-anticipated retries.
But it's not all smooth sailing, for example I'm in a project requiring cookie-based authentication, and I decided to use Ky from the start. However, I quickly ran into an issue... Ky's documentation didn't mention cookies anywhere! After digging into the docs and some trial and error, I found a solution. To save others time, I'm here sharing my approach :).
First, to manage cookies, we'll use tough-cookie, a library that allows you to store, retrieve, and manipulate cookies programmatically. First, install the library and initialize it like so:
import { CookieJar } from "tough-cookie";
const cookieJar = new CookieJar();
Now as I mentioned before, one of the cool features about Ky is their "hooks" right? But what exactly are hooks?
Ky provides hooks, which are functions that run before or after a request. Currently there are four types: beforeRequest
, afterResponse
, beforeError
, and beforeRetry
. For handling cookies specifically, the most useful hooks are beforeRequest
and afterResponse
.
And to use them we need to extend Ky's functionality using ky.extend
. These hooks will automatically handle cookies: beforeRequest
will inject stored cookies into the request headers, and afterResponse
will capture and store new cookies for future requests.
const apiClient = ky.extend({
hooks: {
beforeRequest: [
async (request) => {
const url = request.url;
const cookies = await cookieJar.getCookies(url);
const cookieString = cookies.join("; ");
request.headers.set("cookie", cookieString);
},
],
afterResponse: [
async (request, options, response) => {
const url = request.url;
const cookies = response.headers.getSetCookie();
if (cookies) {
for (const cookie of cookies) {
await cookieJar.setCookie(cookie, url);
}
}
},
],
},
});
The only thing is that everywhere which needs or sets cookies, you will need to use that apiClient
which you just created instead of the plain ky
.
And there you have it! With these simple hooks in place, your Ky requests will automatically handle cookies, saving you time and effort.
I hope this solution helps you as much as it helped me. :)
Have a great day!
Top comments (0)