sindresorhus / ky

🌳 Tiny & elegant JavaScript HTTP client based on the browser Fetch API
MIT License
11.83k stars 341 forks source link

feat: consider cookiejar support #589

Open Thinkscape opened 1 month ago

Thinkscape commented 1 month ago

Quite impressive feature set out of the box.

I'm just missing one, esp. useful for crawling and automation:

Cookie Jar support. I know I could bake that with hooks, but it seems like something that should live in core, given that you've already got lifecycle features like retries and timeouts.

sholladay commented 2 weeks ago

Propose an API.

I would argue that retries and timeouts are universally necessary because networks are unreliable. But cookies are much closer to your application logic.

Thinkscape commented 5 days ago

Well, yes and no.

The credentials: include feature in a server-side fetch is an interesting concept, which is why 'tough-cookie' exists.

API could be as simple as:

import ky from 'ky';
import { CookieJar } from 'tough-cookie';

const cookieJar = new CookieJar();
await ky.post('https://example.com/login', {
  body: "login=foo&password=bar",
  cookieJar
});
console.log(
  'session id =', 
  await cookiejar.getCookies("https://example.com").find(cookie => cookie.key === 'session_id')
);

const response = await ky('https://example.com/dashboard', {
  cookieJar
});

tough-cookie handles most of the hard bits with domains and matching.

Thinkscape commented 5 days ago

It's easy to add with hooks 🤷

Unsure if it needs another separate package, or could live somewhere here

I.e. could be split, and used as:

import { withCookies } from "ky";

const client = ky.create(withCookies()); // registers necessary hooks, consumes tough-cookie
const apiClient = client.extend({ prefixUrl: "http://api.example.com" });
sholladay commented 5 days ago

Seems that got already has this feature.

https://github.com/sindresorhus/got/blob/main/test/cookies.ts

From what I can tell, this is mainly useful for server-side users. But it's a valid use case.