How to use Cookies with Ky

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…


This content originally appeared on DEV Community and was authored by Nícolas Gabriel

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!


This content originally appeared on DEV Community and was authored by Nícolas Gabriel


Print Share Comment Cite Upload Translate Updates
APA

Nícolas Gabriel | Sciencx (2025-02-08T00:53:30+00:00) How to use Cookies with Ky. Retrieved from https://www.scien.cx/2025/02/08/how-to-use-cookies-with-ky/

MLA
" » How to use Cookies with Ky." Nícolas Gabriel | Sciencx - Saturday February 8, 2025, https://www.scien.cx/2025/02/08/how-to-use-cookies-with-ky/
HARVARD
Nícolas Gabriel | Sciencx Saturday February 8, 2025 » How to use Cookies with Ky., viewed ,<https://www.scien.cx/2025/02/08/how-to-use-cookies-with-ky/>
VANCOUVER
Nícolas Gabriel | Sciencx - » How to use Cookies with Ky. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/02/08/how-to-use-cookies-with-ky/
CHICAGO
" » How to use Cookies with Ky." Nícolas Gabriel | Sciencx - Accessed . https://www.scien.cx/2025/02/08/how-to-use-cookies-with-ky/
IEEE
" » How to use Cookies with Ky." Nícolas Gabriel | Sciencx [Online]. Available: https://www.scien.cx/2025/02/08/how-to-use-cookies-with-ky/. [Accessed: ]
rf:citation
» How to use Cookies with Ky | Nícolas Gabriel | Sciencx | https://www.scien.cx/2025/02/08/how-to-use-cookies-with-ky/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.