sindresorhus / ky

🌳 Tiny & elegant JavaScript HTTP client based on the Fetch API

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

feat: consider cookiejar support

Thinkscape opened this issue · comments

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.

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.

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.

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" });

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.