What is tough-cookie?
The tough-cookie npm package is a robust and flexible implementation of HTTP cookies, allowing for the parsing, manipulation, and serialization of cookie headers. It provides a way to manage cookies for HTTP clients, including support for persistence, cookie jars, and the ability to handle various cookie-related operations as per the RFC 6265 standard.
What are tough-cookie's main functionalities?
Cookie Parsing
This feature allows for the parsing of cookie header strings into Cookie objects, which can then be manipulated or stored.
const Cookie = require('tough-cookie').Cookie;
const cookie = Cookie.parse('key=value; expires=Wed, 09 Jun 2021 10:18:14 GMT');
Cookie Serialization
This feature enables the serialization of Cookie objects back into HTTP header strings, which can be used in HTTP requests.
const Cookie = require('tough-cookie').Cookie;
const cookie = new Cookie({key: 'value', domain: 'example.com', path: '/'});
const header = cookie.toString();
Cookie Jar
The Cookie Jar feature allows for the storage and retrieval of cookies across multiple requests, maintaining state and handling cookie scope such as domain and path.
const { CookieJar } = require('tough-cookie');
const jar = new CookieJar();
jar.setCookieSync('key=value; Domain=example.com', 'http://example.com', { http: true });
Cookie Store Persistence
This feature provides a way to persist cookies between sessions by using a file-based store or other custom store implementations.
const { CookieJar, FileCookieStore } = require('tough-cookie');
const jar = new CookieJar(new FileCookieStore('cookies.json'));
// Cookies within the jar will be persisted to 'cookies.json' file.
Other packages similar to tough-cookie
js-cookie
js-cookie is a simple, lightweight JavaScript API for handling cookies. It works well in the browser and has a simpler API but does not have the Node.js environment support or the advanced features such as cookie jars and persistence that tough-cookie offers.
cookie
The cookie npm package is a simple server-side cookie parsing and serialization library. It is more minimalistic compared to tough-cookie and does not provide a cookie jar or persistence features.
cookies
The cookies package is designed for use with Node.js HTTP servers. It provides cookie parsing and serialization similar to tough-cookie but is tailored for server-side use and does not include a cookie jar implementation.
Tough Cookie ·
A Node.js implementation of RFC6265 for cookie parsing, storage, and retrieval.
Getting Started
Install Tough Cookie using npm
:
npm install tough-cookie
or yarn
:
yarn add tough-cookie
Usage
import { Cookie, CookieJar } from 'tough-cookie'
const reqCookies = 'ID=298zf09hf012fh2; csrf=u32t4o3tb3gg43; _gat=1'.split(';').map(Cookie.parse)
const cookieHeader = reqCookies.map(cookie => cookie.cookieString()).join(';')
const resCookie = Cookie.parse('foo=bar; Domain=example.com; Path=/; Expires=Tue, 21 Oct 2025 00:00:00 GMT')
const setCookieHeader = cookie.toString()
const cookieJar = new CookieJar()
await cookieJar.setCookie(resCookie, 'https://example.com/')
const matchingCookies = await cookieJar.getCookies('https://example.com/')
[!IMPORTANT]
For more detailed usage information, refer to the API docs.
RFC6265bis
Support for RFC6265bis is being developed. As these revisions to RFC6252 are
still in Active Internet-Draft
state, the areas of support that follow are subject to change.
SameSite Cookies
This change makes it possible for servers, and supporting clients, to mitigate certain types of CSRF
attacks by disallowing SameSite
cookies from being sent cross-origin.
Example
import { CookieJar } from 'tough-cookie'
const cookieJar = new CookieJar()
await cookieJar.setCookie('strict=authorized; SameSite=strict', 'http://example.com/index.html')
await cookieJar.setCookie('lax=okay; SameSite=lax', 'http://example.com/index.html')
await cookieJar.setCookie('normal=whatever', 'http://example.com/index.html')
const laxCookies = await cookieJar.getCookies('http://example.com/index.html', {
sameSiteContext: 'lax',
})
[!NOTE]
It is highly recommended that you read RFC6265bis - Section 8.8 for more details on SameSite cookies, security considerations, and defense in depth.
Cookie Prefixes
Cookie prefixes are a way to indicate that a given cookie was set with a set of attributes simply by
inspecting the first few characters of the cookie's name.
Two prefixes are defined:
-
"__Secure-"
If a cookie's name begins with a case-sensitive match for the string __Secure-
, then the cookie was set with a "Secure" attribute.
-
"__Host-"
If a cookie's name begins with a case-sensitive match for the string __Host-
, then the cookie was set with a "Secure" attribute, a "Path" attribute with a value of "/", and no "Domain" attribute.
If prefixSecurity
is enabled for CookieJar
, then cookies that match the prefixes defined above but do
not obey the attribute restrictions are not added.
You can define this functionality by passing in the prefixSecurity
option to CookieJar
. It can be one of 3 values:
silent
: (default) Enable cookie prefix checking but silently fail to add the cookie if conditions are not met.strict
: Enable cookie prefix checking and error out if conditions are not met.unsafe-disabled
: Disable cookie prefix checking.
If ignoreError
is passed in as true
when setting a cookie then the error is silent regardless of the prefixSecurity
option (assuming it's enabled).
Example
import { CookieJar, MemoryCookieStore } from 'tough-cookie'
const cookieJar = new CookieJar(new MemoryCookieStore(), {
prefixSecurity: 'silent'
})
await cookieJar.setCookie(
'__Secure-SID=12345; Domain=example.com; Secure;',
'http://example.com',
)
await cookieJar.setCookie(
'__Secure-SID=12345; Domain=example.com; Secure;',
'https://example.com',
)
[!NOTE]
It is highly recommended that you read RFC6265bis - Section 4.1.3 for more details on Cookie Prefixes.
Node.js Version Support
We follow the Node.js release schedule and support
all versions that are in Active LTS or Maintenance. We will always do a major release when dropping support
for older versions of node, and we will do so in consultation with our community.