Product
Introducing Java Support in Socket
We're excited to announce that Socket now supports the Java programming language.
fetch-cookie
Advanced tools
The fetch-cookie npm package is a wrapper around the Fetch API that adds automatic handling of cookies. It allows you to manage cookies in a more convenient way when making HTTP requests, which is particularly useful for maintaining session state across multiple requests.
Automatic Cookie Handling
This feature allows you to automatically handle cookies when making HTTP requests. The cookies are stored and sent with subsequent requests to the same domain, making it easier to manage session state.
const fetch = require('fetch-cookie/node-fetch')(require('node-fetch'));
fetch('https://example.com')
.then(res => res.text())
.then(body => console.log(body));
Custom Cookie Jar
You can use a custom cookie jar to manage cookies. This is useful if you need to share cookies between different parts of your application or if you need to persist cookies between sessions.
const fetch = require('fetch-cookie/node-fetch')(require('node-fetch'));
const tough = require('tough-cookie');
const cookieJar = new tough.CookieJar();
fetch('https://example.com', { cookieJar })
.then(res => res.text())
.then(body => console.log(body));
Integration with Node.js and Browsers
The package can be used both in Node.js and in browser environments, making it versatile for different types of applications.
const fetch = require('fetch-cookie/node-fetch')(require('node-fetch'));
fetch('https://example.com')
.then(res => res.text())
.then(body => console.log(body));
Axios is a promise-based HTTP client for the browser and Node.js. It supports automatic transformation of JSON data, and you can use it with the 'axios-cookiejar-support' package to handle cookies similarly to fetch-cookie.
Request is a simplified HTTP client for Node.js with support for many features, including cookie handling via the 'request-promise-native' package. However, it is now deprecated and not recommended for new projects.
Superagent is a small, progressive client-side HTTP request library that also works in Node.js. It supports cookies out of the box and provides a similar level of functionality for managing cookies.
Decorator for a
fetch
function to support automatic cookie storage and population.
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.
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)
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
}
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
}))
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.
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 })
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.
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.
# 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
[3.0.1] - 2024-02-24
FAQs
Decorator for a `fetch` function to support automatic cookies.
The npm package fetch-cookie receives a total of 542,274 weekly downloads. As such, fetch-cookie popularity was classified as popular.
We found that fetch-cookie demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
We're excited to announce that Socket now supports the Java programming language.
Security News
Socket detected a malicious Python package impersonating a popular browser cookie library to steal passwords, screenshots, webcam images, and Discord tokens.
Security News
Deno 2.0 is now available with enhanced package management, full Node.js and npm compatibility, improved performance, and support for major JavaScript frameworks.