npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

fetch-cookie

v3.0.1

Published

Decorator for a `fetch` function to support automatic cookies.

Downloads

3,077,431

Readme

🍪 fetch-cookie npm version Build status

Decorator for a fetch function to support automatic cookie storage and population.

Migrating from v1

Description

fetch-cookie wraps around a fetch function and intercepts request options and response objects to store received cookies and populate request with the appropriate cookies.

This library is developed with Node.js and fetch polyfill libraries such as node-fetch in mind, since the browser version is supposed to let a way to include cookies in requests. Compatibility may not be guaranteed but as long as your library implements the Fetch standard you should be fine. In case of incompatibilities, please create a new issue.

Internally the plugin uses a cookie jar. You can insert your own (details below) but tough-cookie is preferred.

Usage

With Node.js 18.3.0 and greater, using the native global fetch function:

import makeFetchCookie from 'fetch-cookie'

const fetchCookie = makeFetchCookie(fetch)

Or with node-fetch:

import nodeFetch from 'node-fetch'
import fetchCookie from 'fetch-cookie'

const fetch = fetchCookie(nodeFetch)

Custom cookie jar

If you want to customize the internal cookie jar instance (for example, with a custom store), you can inject it as a second argument:

import makeFetchCookie from 'fetch-cookie'

const fetchCookie = makeFetchCookie(fetch, new makeFetchCookie.toughCookie.CookieJar())

Here, we expose the tough-cookie version that we depend on internally so you can just reuse it and don't end up accidentally bundling two different versions. That being said you can use any version of tough-cookie here, or even any compatible cookie jar.

This enables you to create multiple fetch-cookie instances that use different cookie jars, essentially two different HTTP clients with different login sessions on you backend (for example).

All calls to fetch will store and send back cookies according to the URL.

If you use a cookie jar that is not tough-cookie, keep in mind that it must implement this interface to be compatible:

interface CookieJar {
  getCookieString(currentUrl: string): Promise<string>
  setCookie(cookieString: string, currentUrl: string, opts: { ignoreError: boolean }): Promise
}

Custom cookie jar with options

If you don't want a custom store and just want to pass tough-cookie options, e.g. to allow cookies on localhost:

import makeFetchCookie from 'fetch-cookie'

const fetchCookie = makeFetchCookie(fetch, new makeFetchCookie.toughCookie.CookieJar(undefined, {
  allowSpecialUseDomain: true
}))

Or with a custom store as well:

import makeFetchCookie from 'fetch-cookie'
import FileCookieStore from 'file-cookie-store'

const store = new FileCookieStore('cookies.txt')

const fetchCookie = makeFetchCookie(fetch, new makeFetchCookie.toughCookie.CookieJar(store, {
  allowSpecialUseDomain: true
}))

Ignoring errors

All errors when setting cookies are ignored by default. You can make it throw errors in cookies by passing a third argument ignoreError (defaulting to true).

import makeFetchCookie from 'fetch-cookie'

const fetchCookie = makeFetchCookie(fetch, new makeFetchCookie.toughCookie.CookieJar(), false)

When set to false, fetch-cookie will throw when an error occurs in setting cookies and breaks the request and execution.

Otherwise, it silently ignores errors and continues to make requests/redirections.

Max redirects

Because we need to do our own redirect implementation, the way to configure the max redirects is not going to be that of your chosen fetch implementation, but custom to fetch-cookie.

We read a maxRedirect parameter for that. The default is 20.

import makeFetchCookie from 'fetch-cookie'

const fetchCookie = makeFetchCookie(fetch)

await fetchCookie(url, { maxRedirect: 10 })

Cookies on redirects

In order to handle cookies on redirects, we force the redirect parameter to manual, and handle the redirections internally (according to the original redirect value) instead of leaving it to the upstream fetch implementation.

This allows us to hook into the redirect logic in order to store and forward cookies accordingly.

This is useful for example when a login page sets a session cookie and redirects to another page.

Migrating from v1

The only breaking change with v2 is that the node-fetch wrapper (that was handling redirects only with node-fetch nonstandard APIs) was dropped and the redirects are now always handled by the main export.

// If you were doing
const fetchCookie = require('fetch-cookie/node-fetch')

// Change it to
const fetchCookie = require('fetch-cookie')

// Or
import fetchCookie from 'fetch-cookie'

This also means that if you were not using the node-fetch wrapper and were happy about cookies not being included in redirects, cookies are now going to be stored and sent in redirects as well like they would in the browser.

Development

# Install dependencies
npm ci

# Allows to test node-fetch v2 as well as node-fetch v3
npm --prefix test/node_modules/node-fetch-2 ci

# Allows to test against Undici by removing the blacklisting of `Set-Cookie` headers
npm run patch-undici

npm run lint
npm run type-check

# Generates code in `esm` and `cjs` directories
npm run build

# Run tests (depends on the built code)
npm test

# Generate type declarations in the `types` directory
npm run type-declarations

Credits

  • 🥰 All the contributors to fetch-cookie!
  • 😍 node-fetch for the redirect logic that we carefully mimic (sadly reimplementing this code was the only way to support cookies in redirects).