HTTP Cookie Agent

7.0.3 · active · verified Tue Apr 21

http-cookie-agent is a Node.js library that provides HTTP(S) agents capable of managing cookies across various popular HTTP clients, including Node.js global fetch (via undici), undici directly, axios, node-fetch, and the native `node:http`/`node:https` modules. Its current stable version is 7.0.3, with minor bug fix releases occurring relatively frequently and major versions released annually or as significant changes warrant. The library primarily differentiates itself by offering a unified cookie management solution that integrates seamlessly with existing `tough-cookie` instances and supports a wide array of HTTP client libraries, allowing developers to centralize cookie handling in complex Node.js applications without reimplementing logic for each client. It requires `tough-cookie` and, for `fetch` integration, `undici` as peer dependencies.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to initialize `CookieJar` and `CookieAgent` for `undici` (or Node.js global `fetch`), making two requests to `httpbin.org` to set and then retrieve a cookie.

import { CookieJar } from 'tough-cookie';
import { CookieAgent } from 'http-cookie-agent/undici';
import { fetch } from 'undici'; // Or use global fetch if undici is installed for Node.js >=20

async function makeRequestWithCookies() {
  const jar = new CookieJar();
  const agent = new CookieAgent({ cookies: { jar } });

  console.log('Sending first request to set a cookie...');
  const firstResponse = await fetch('https://httpbin.org/cookies/set?mycookie=myvalue', {
    dispatcher: agent
  });
  console.log(`First request status: ${firstResponse.status}`);
  await firstResponse.text(); // Consume body to ensure cookies are processed

  console.log('Sending second request to retrieve the cookie...');
  const secondResponse = await fetch('https://httpbin.org/cookies', {
    dispatcher: agent
  });
  console.log(`Second request status: ${secondResponse.status}`);
  const cookieData = await secondResponse.json();
  console.log('Cookies received in second request:', cookieData.cookies);

  if (cookieData.cookies.mycookie === 'myvalue') {
    console.log('Success: Cookie was correctly sent and received!');
  } else {
    console.log('Failure: Cookie was not handled as expected.');
  }
}

makeRequestWithCookies().catch(console.error);

view raw JSON →