tough-cookie

  • Version 5.0.0
  • Published
  • 225 kB
  • 1 dependency
  • BSD-3-Clause license

Install

npm i tough-cookie
yarn add tough-cookie
pnpm add tough-cookie

Overview

RFC6265 Cookies and Cookie Jar for node.js

Index

Variables

Functions

Classes

Interfaces

Type Aliases

Variables

variable PrefixSecurityEnum

const PrefixSecurityEnum: Readonly<{
SILENT: 'silent';
STRICT: 'strict';
DISABLED: 'unsafe-disabled';
}>;
  • 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. These are defined in RFC6265bis - Section 4.1.3.

    The following values can be used to configure how a CookieJar enforces attribute restrictions for Cookie prefixes:

    - silent - Enable cookie prefix checking but silently ignores the cookie if conditions are not met. This is the default configuration for a CookieJar.

    - strict - Enables cookie prefix checking and will raise an error if conditions are not met.

    - unsafe-disabled - Disables cookie prefix checking.

    Modifiers

    • @public

variable version

const version: string;
  • The version of tough-cookie

    Modifiers

    • @public

Functions

function canonicalDomain

canonicalDomain: (domainName: Nullable<string>) => string | undefined;
  • Transforms a domain name into a canonical domain name. The canonical domain name is a domain name that has been trimmed, lowercased, stripped of leading dot, and optionally punycode-encoded (Section 5.1.2 of RFC 6265). For the most part, this function is idempotent (calling the function with the output from a previous call returns the same output).

    Parameter domainName

    the domain name to generate the canonical domain from

    Remarks

    A canonicalized host name is the string generated by the following algorithm:

    1. Convert the host name to a sequence of individual domain name labels.

    2. Convert each label that is not a Non-Reserved LDH (NR-LDH) label, to an A-label (see Section 2.3.2.1 of [RFC5890] for the former and latter), or to a "punycode label" (a label resulting from the "ToASCII" conversion in Section 4 of [RFC3490]), as appropriate (see Section 6.3 of this specification).

    3. Concatenate the resulting labels, separated by a %x2E (".") character.

    Example 1

    canonicalDomain('.EXAMPLE.com') === 'example.com'

    Modifiers

    • @public

function cookieCompare

cookieCompare: (a: Cookie, b: Cookie) => number;
  • A comparison function that can be used with Array.sort(), which orders a list of cookies into the recommended order given in Step 2 of RFC6265 - Section 5.4.

    The sort algorithm is, in order of precedence:

    - Longest Cookie.path

    - Oldest Cookie.creation (which has a 1-ms precision, same as Date)

    - Lowest Cookie.creationIndex (to get beyond the 1-ms precision)

    Parameter a

    the first Cookie for comparison

    Parameter b

    the second Cookie for comparison

    Remarks

    ### RFC6265 - Section 5.4 - Step 2

    The user agent SHOULD sort the cookie-list in the following order:

    - Cookies with longer paths are listed before cookies with shorter paths.

    - Among cookies that have equal-length path fields, cookies with earlier creation-times are listed before cookies with later creation-times.

    NOTE: Not all user agents sort the cookie-list in this order, but this order reflects common practice when this document was written, and, historically, there have been servers that (erroneously) depended on this order.

    ### Custom Store Implementors

    Since the JavaScript Date is limited to a 1-ms precision, cookies within the same millisecond are entirely possible. This is especially true when using the now option to CookieJar.setCookie(...). The Cookie.creationIndex property is a per-process global counter, assigned during construction with new Cookie(), which preserves the spirit of the RFC sorting: older cookies go first. This works great for MemoryCookieStore since Set-Cookie headers are parsed in order, but is not so great for distributed systems.

    Sophisticated Stores may wish to set this to some other logical clock so that if cookies A and B are created in the same millisecond, but cookie A is created before cookie B, then A.creationIndex < B.creationIndex.

    Example 1

    const cookies = [
    new Cookie({ key: 'a', value: '' }),
    new Cookie({ key: 'b', value: '' }),
    new Cookie({ key: 'c', value: '', path: '/path' }),
    new Cookie({ key: 'd', value: '', path: '/path' }),
    ]
    cookies.sort(cookieCompare)
    // cookie sort order would be ['c', 'd', 'a', 'b']

    Modifiers

    • @public

function defaultPath

defaultPath: (path?: Nullable<string>) => string;
  • Given a current request/response path, gives the path appropriate for storing in a cookie. This is basically the "directory" of a "file" in the path, but is specified by RFC6265 - Section 5.1.4.

    Parameter path

    the path portion of the request-uri (excluding the hostname, query, fragment, and so on)

    Remarks

    ### RFC6265 - Section 5.1.4

    The user agent MUST use an algorithm equivalent to the following algorithm to compute the default-path of a cookie:

    1. Let uri-path be the path portion of the request-uri if such a portion exists (and empty otherwise). For example, if the request-uri contains just a path (and optional query string), then the uri-path is that path (without the %x3F ("?") character or query string), and if the request-uri contains a full absoluteURI, the uri-path is the path component of that URI.

    2. If the uri-path is empty or if the first character of the uri- path is not a %x2F ("/") character, output %x2F ("/") and skip the remaining steps.

    3. If the uri-path contains no more than one %x2F ("/") character, output %x2F ("/") and skip the remaining step.

    4. Output the characters of the uri-path from the first character up to, but not including, the right-most %x2F ("/").

    Example 1

    defaultPath('') === '/'
    defaultPath('/some-path') === '/'
    defaultPath('/some-parent-path/some-path') === '/some-parent-path'
    defaultPath('relative-path') === '/'

    Modifiers

    • @public

function domainMatch

domainMatch: (
domain?: Nullable<string>,
cookieDomain?: Nullable<string>,
canonicalize?: boolean
) => boolean | undefined;
  • Answers "does this real domain match the domain in a cookie?". The domain is the "current" domain name and the cookieDomain is the "cookie" domain name. Matches according to RFC6265 - Section 5.1.3, but it helps to think of it as a "suffix match".

    Parameter domain

    The domain string to test

    Parameter cookieDomain

    The cookie domain string to match against

    Parameter canonicalize

    The canonicalize parameter toggles whether the domain parameters get normalized with canonicalDomain or not

    Remarks

    ### 5.1.3. Domain Matching

    A string domain-matches a given domain string if at least one of the following conditions hold:

    - The domain string and the string are identical. (Note that both the domain string and the string will have been canonicalized to lower case at this point.)

    - All of the following conditions hold:

    - The domain string is a suffix of the string.

    - The last character of the string that is not included in the domain string is a %x2E (".") character.

    - The string is a host name (i.e., not an IP address).

    Example 1

    domainMatch('example.com', 'example.com') === true
    domainMatch('eXaMpLe.cOm', 'ExAmPlE.CoM') === true
    domainMatch('no.ca', 'yes.ca') === false

    Modifiers

    • @public

function formatDate

formatDate: (date: Date) => string;

function fromJSON

fromJSON: (str: unknown) => Cookie | undefined;

function getPublicSuffix

getPublicSuffix: (
domain: string,
options?: GetPublicSuffixOptions
) => string | undefined;
  • Returns the public suffix of this hostname. The public suffix is the shortest domain name upon which a cookie can be set.

    Parameter domain

    the domain attribute of a cookie

    Parameter options

    optional configuration for controlling how the public suffix is determined

    Remarks

    A "public suffix" is a domain that is controlled by a public registry, such as "com", "co.uk", and "pvt.k12.wy.us". This step is essential for preventing attacker.com from disrupting the integrity of example.com by setting a cookie with a Domain attribute of "com". Unfortunately, the set of public suffixes (also known as "registry controlled domains") changes over time. If feasible, user agents SHOULD use an up-to-date public suffix list, such as the one maintained by the Mozilla project at http://publicsuffix.org/. (See RFC6265 - Section 5.3)

    Example 1

    getPublicSuffix('www.example.com') === 'example.com'
    getPublicSuffix('www.subdomain.example.com') === 'example.com'

    Modifiers

    • @public

function parse

parse: (str: string, options?: ParseCookieOptions) => Cookie | undefined;

function parseDate

parseDate: (cookieDate: Nullable<string>) => Date | undefined;
  • Parse a cookie date string into a Date. Parses according to RFC6265 - Section 5.1.1, not Date.parse().

    Parameter cookieDate

    the cookie date string

    Remarks

    ### RFC6265 - 5.1.1. Dates

    The user agent MUST use an algorithm equivalent to the following algorithm to parse a cookie-date. Note that the various boolean flags defined as a part of the algorithm (i.e., found-time, found- day-of-month, found-month, found-year) are initially "not set".

    1. Using the grammar below, divide the cookie-date into date-tokens.

    cookie-date = *delimiter date-token-list *delimiter
    date-token-list = date-token *( 1*delimiter date-token )
    date-token = 1*non-delimiter
    delimiter = %x09 / %x20-2F / %x3B-40 / %x5B-60 / %x7B-7E
    non-delimiter = %x00-08 / %x0A-1F / DIGIT / ":" / ALPHA / %x7F-FF
    non-digit = %x00-2F / %x3A-FF
    day-of-month = 1*2DIGIT ( non-digit *OCTET )
    month = ( "jan" / "feb" / "mar" / "apr" /
    "may" / "jun" / "jul" / "aug" /
    "sep" / "oct" / "nov" / "dec" ) *OCTET
    year = 2*4DIGIT ( non-digit *OCTET )
    time = hms-time ( non-digit *OCTET )
    hms-time = time-field ":" time-field ":" time-field
    time-field = 1*2DIGIT

    2. Process each date-token sequentially in the order the date-tokens appear in the cookie-date:

    1. If the found-time flag is not set and the token matches the time production, set the found-time flag and set the hour- value, minute-value, and second-value to the numbers denoted by the digits in the date-token, respectively. Skip the remaining sub-steps and continue to the next date-token.

    2. If the found-day-of-month flag is not set and the date-token matches the day-of-month production, set the found-day-of- month flag and set the day-of-month-value to the number denoted by the date-token. Skip the remaining sub-steps and continue to the next date-token.

    3. If the found-month flag is not set and the date-token matches the month production, set the found-month flag and set the month-value to the month denoted by the date-token. Skip the remaining sub-steps and continue to the next date-token.

    4. If the found-year flag is not set and the date-token matches the year production, set the found-year flag and set the year-value to the number denoted by the date-token. Skip the remaining sub-steps and continue to the next date-token.

    3. If the year-value is greater than or equal to 70 and less than or equal to 99, increment the year-value by 1900.

    4. If the year-value is greater than or equal to 0 and less than or equal to 69, increment the year-value by 2000.

    1. NOTE: Some existing user agents interpret two-digit years differently.

    5. Abort these steps and fail to parse the cookie-date if:

    - at least one of the found-day-of-month, found-month, found- year, or found-time flags is not set,

    - the day-of-month-value is less than 1 or greater than 31,

    - the year-value is less than 1601,

    - the hour-value is greater than 23,

    - the minute-value is greater than 59, or

    - the second-value is greater than 59.

    (Note that leap seconds cannot be represented in this syntax.)

    6. Let the parsed-cookie-date be the date whose day-of-month, month, year, hour, minute, and second (in UTC) are the day-of-month- value, the month-value, the year-value, the hour-value, the minute-value, and the second-value, respectively. If no such date exists, abort these steps and fail to parse the cookie-date.

    7. Return the parsed-cookie-date as the result of this algorithm.

    Example 1

    parseDate('Wed, 09 Jun 2021 10:18:14 GMT')

    Modifiers

    • @public

function pathMatch

pathMatch: (reqPath: string, cookiePath: string) => boolean;
  • Answers "does the request-path path-match a given cookie-path?" as per RFC6265 Section 5.1.4. This is essentially a prefix-match where cookiePath is a prefix of reqPath.

    Parameter reqPath

    the path of the request

    Parameter cookiePath

    the path of the cookie

    Remarks

    A request-path path-matches a given cookie-path if at least one of the following conditions holds:

    - The cookie-path and the request-path are identical. - The cookie-path is a prefix of the request-path, and the last character of the cookie-path is %x2F ("/"). - The cookie-path is a prefix of the request-path, and the first character of the request-path that is not included in the cookie-path is a %x2F ("/") character.

    Modifiers

    • @public

function permuteDomain

permuteDomain: (
domain: string,
allowSpecialUseDomain?: boolean
) => string[] | undefined;
  • Generates the permutation of all possible values that domainMatch the given domain parameter. The array is in shortest-to-longest order. Useful when building custom Store implementations.

    Parameter domain

    the domain to generate permutations for

    Parameter allowSpecialUseDomain

    flag to control if Special Use Domains such as localhost should be allowed

    Example 1

    permuteDomain('foo.bar.example.com')
    // ['example.com', 'bar.example.com', 'foo.bar.example.com']

    Modifiers

    • @public

function permutePath

permutePath: (path: string) => string[];
  • Generates the permutation of all possible values that pathMatch the path parameter. The array is in longest-to-shortest order. Useful when building custom Store implementations.

    Parameter path

    the path to generate permutations for

    Example 1

    permutePath('/foo/bar/')
    // ['/foo/bar/', '/foo/bar', '/foo', '/']

    Modifiers

    • @public

Classes

class Cookie {}
  • An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to a user's web browser. It is defined in RFC6265.

    Modifiers

    • @public

constructor

constructor(options?: CreateCookieOptions);
  • Create a new Cookie instance.

    Parameter options

    The attributes to set on the cookie

    Modifiers

    • @public

property creation

creation: Date | 'Infinity';
  • Set to the date and time when a Cookie is initially stored or a matching cookie is received that replaces an existing cookie (See RFC6265 Section 5.3).

    Also used to maintain ordering among cookies. Among cookies that have equal-length path fields, cookies with earlier creation-times are listed before cookies with later creation-times (See RFC6265 Section 5.4).

property creationIndex

creationIndex: number;
  • A global counter used to break ordering ties between two cookies that have equal-length path fields and the same creation-time.

property domain

domain: string;
  • The 'Domain' attribute of the cookie represents the domain the cookie belongs to (See RFC6265 Section 5.2.3).

property expires

expires: Date | 'Infinity';

property extensions

extensions: string[];
  • Contains attributes which are not part of the defined spec but match the extension-av syntax defined in Section 4.1.1 of RFC6265 (See RFC6265 Section 4.1.1).

property hostOnly

hostOnly: boolean;
  • A boolean flag indicating if a cookie is a host-only cookie (i.e.; when the request's host exactly matches the domain of the cookie) or not (See RFC6265 Section 5.3).

property httpOnly

httpOnly: boolean;
  • The 'HttpOnly' flag of the cookie indicates if the cookie is inaccessible to client scripts or not (See RFC6265 Section 5.2.6).

property key

key: string;
  • The name or key of the cookie

property lastAccessed

lastAccessed: Date | 'Infinity';

property maxAge

maxAge: number | 'Infinity' | '-Infinity';

property path

path: string;

property pathIsDefault

pathIsDefault: boolean;
  • A boolean flag indicating if a cookie had no 'Path' attribute and the default path was used (See RFC6265 Section 5.2.4).

property sameSite

sameSite: string;

property secure

secure: boolean;
  • The 'Secure' flag of the cookie indicates if the scope of the cookie is limited to secure channels (e.g.; HTTPS) or not (See RFC6265 Section 5.2.5).

property serializableProperties

static serializableProperties: readonly [
'key',
'value',
'expires',
'maxAge',
'domain',
'path',
'secure',
'httpOnly',
'extensions',
'hostOnly',
'pathIsDefault',
'creation',
'lastAccessed',
'sameSite'
];

property value

value: string;
  • The value of the cookie

method canonicalizedDomain

canonicalizedDomain: () => string | undefined;

method cdomain

cdomain: () => string | undefined;

method clone

clone: () => Cookie | undefined;
  • Does a deep clone of this cookie, implemented exactly as Cookie.fromJSON(cookie.toJSON()).

    Modifiers

    • @public

method cookieString

cookieString: () => string;
  • Encodes to a Cookie header value (specifically, the Cookie.key and Cookie.value properties joined with "=").

    Modifiers

    • @public

method expiryTime

expiryTime: (now?: Date) => number | undefined;
  • Computes the absolute unix-epoch milliseconds that this cookie expires.

    The "Max-Age" attribute takes precedence over "Expires" (as per the RFC). The Cookie.lastAccessed attribute (or the now parameter if given) is used to offset the Cookie.maxAge attribute.

    If Expires (Cookie.expires) is set, that's returned.

    Parameter now

    can be used to provide a time offset (instead of Cookie.lastAccessed) to use when calculating the "Max-Age" value

method fromJSON

static fromJSON: (str: unknown) => Cookie | undefined;
  • Does the reverse of Cookie.toJSON.

    Parameter str

    An unparsed JSON string or a value that has already been parsed as JSON

    Remarks

    Any Date properties (such as .expires, .creation, and .lastAccessed) are parsed via Date.parse, not tough-cookie's parseDate, since ISO timestamps are being handled at this layer.

    Example 1

    const json = JSON.stringify({
    key: 'alpha',
    value: 'beta',
    domain: 'example.com',
    path: '/foo',
    expires: '2038-01-19T03:14:07.000Z',
    })
    const cookie = Cookie.fromJSON(json)
    cookie.key === 'alpha'
    cookie.value === 'beta'
    cookie.domain === 'example.com'
    cookie.path === '/foo'
    cookie.expires === new Date(Date.parse('2038-01-19T03:14:07.000Z'))

method isPersistent

isPersistent: () => boolean;
  • Indicates if the cookie has been persisted to a store or not.

    Modifiers

    • @public

method parse

static parse: (str: string, options?: ParseCookieOptions) => Cookie | undefined;
  • Parses a string into a Cookie object.

    Parameter str

    The Set-Cookie header or a Cookie string to parse.

    Parameter options

    Configures strict or loose mode for cookie parsing

    Remarks

    Note: when parsing a Cookie header it must be split by ';' before each Cookie string can be parsed.

    Example 1

    // parse a `Set-Cookie` header
    const setCookieHeader = 'a=bcd; Expires=Tue, 18 Oct 2011 07:05:03 GMT'
    const cookie = Cookie.parse(setCookieHeader)
    cookie.key === 'a'
    cookie.value === 'bcd'
    cookie.expires === new Date(Date.parse('Tue, 18 Oct 2011 07:05:03 GMT'))

    Example 2

    // parse a `Cookie` header
    const cookieHeader = 'name=value; name2=value2; name3=value3'
    const cookies = cookieHeader.split(';').map(Cookie.parse)
    cookies[0].name === 'name'
    cookies[0].value === 'value'
    cookies[1].name === 'name2'
    cookies[1].value === 'value2'
    cookies[2].name === 'name3'
    cookies[2].value === 'value3'

method setExpires

setExpires: (exp: string | Date) => void;
  • Sets the 'Expires' attribute on a cookie.

    Parameter exp

    the new value for the 'Expires' attribute of the cookie.

    Remarks

    When given a string value it will be parsed with parseDate. If the value can't be parsed as a cookie date then the 'Expires' attribute will be set to "Infinity".

method setMaxAge

setMaxAge: (age: number) => void;
  • Sets the 'Max-Age' attribute (in seconds) on a cookie.

    Parameter age

    the new value for the 'Max-Age' attribute (in seconds).

    Remarks

    Coerces -Infinity to "-Infinity" and Infinity to "Infinity" so it can be serialized to JSON.

method toJSON

toJSON: () => SerializedCookie;
  • For convenience in using JSON.stringify(cookie). Returns a plain-old Object that can be JSON-serialized.

    Remarks

    - Any Date properties (such as Cookie.expires, Cookie.creation, and Cookie.lastAccessed) are exported in ISO format (Date.toISOString()).

    - Custom Cookie properties are discarded. In tough-cookie 1.x, since there was no Cookie.toJSON method explicitly defined, all enumerable properties were captured. If you want a property to be serialized, add the property name to Cookie.serializableProperties.

method toString

toString: () => string;
  • Encodes to a Set-Cookie header value.

    Modifiers

    • @public

method TTL

TTL: (now?: number) => number;
  • Computes the TTL relative to now (milliseconds).

    Parameter now

    passing an explicit value is mostly used for testing purposes since this defaults to the Date.now()

    Remarks

    - Infinity is returned for cookies without an explicit expiry

    - 0 is returned if the cookie is expired.

    - Otherwise a time-to-live in milliseconds is returned.

    Modifiers

    • @public

method validate

validate: () => boolean;
  • Validates cookie attributes for semantic correctness. Useful for "lint" checking any Set-Cookie headers you generate. For now, it returns a boolean, but eventually could return a reason string.

    Remarks

    Works for a few things, but is by no means comprehensive.

    Modifiers

    • @beta

class CookieJar

class CookieJar {}
  • A CookieJar is for storage and retrieval of Cookie objects as defined in RFC6265 - Section 5.3.

    It also supports a pluggable persistence layer via Store.

    Modifiers

    • @public

constructor

constructor(store?: Store, options?: boolean | CreateCookieJarOptions);
  • Creates a new CookieJar instance.

    Parameter store

    a custom Store implementation (defaults to MemoryCookieStore)

    Parameter options

    configures how cookies are processed by the cookie jar

    Remarks

    - If a custom store is not passed to the constructor, an in-memory store (MemoryCookieStore will be created and used. - If a boolean value is passed as the options parameter, this is equivalent to passing { rejectPublicSuffixes: <value> }

property prefixSecurity

readonly prefixSecurity: string;

property store

readonly store: Store;

method clone

clone: {
(callback: Callback<CookieJar>): void;
(newStore: Store, callback: Callback<CookieJar>): void;
(newStore?: Store): Promise<CookieJar>;
};
  • Produces a deep clone of this CookieJar. Modifications to the original do not affect the clone, and vice versa.

    Parameter callback

    A function to call when the CookieJar is cloned.

    Remarks

    - When no Store is provided, a new MemoryCookieStore will be used.

    - Transferring between store types is supported so long as the source implements .getAllCookies() and the destination implements .putCookie().

  • Produces a deep clone of this CookieJar. Modifications to the original do not affect the clone, and vice versa.

    Parameter newStore

    The target Store to clone cookies into.

    Parameter callback

    A function to call when the CookieJar is cloned.

    Remarks

    - When no Store is provided, a new MemoryCookieStore will be used.

    - Transferring between store types is supported so long as the source implements .getAllCookies() and the destination implements .putCookie().

  • Produces a deep clone of this CookieJar. Modifications to the original do not affect the clone, and vice versa.

    Parameter newStore

    The target Store to clone cookies into.

    Remarks

    - When no Store is provided, a new MemoryCookieStore will be used.

    - Transferring between store types is supported so long as the source implements .getAllCookies() and the destination implements .putCookie().

method cloneSync

cloneSync: (newStore?: Store) => CookieJar | undefined;
  • Produces a deep clone of this CookieJar. Modifications to the original do not affect the clone, and vice versa.

    Note: Only works if both the configured Store and destination Store are synchronous.

    Parameter newStore

    The target Store to clone cookies into.

    Remarks

    - When no Store is provided, a new MemoryCookieStore will be used.

    - Transferring between store types is supported so long as the source implements .getAllCookies() and the destination implements .putCookie().

method deserialize

static deserialize: {
(strOrObj: string | object, callback: Callback<CookieJar>): void;
(
strOrObj: string | object,
store: Store,
callback: Callback<CookieJar>
): void;
(strOrObj: string | object, store?: Store): Promise<CookieJar>;
(
strOrObj: string | object,
store?: Store | Callback<CookieJar>,
callback?: Callback<CookieJar>
): unknown;
};
  • A new CookieJar is created and the serialized Cookie values are added to the underlying store. Each Cookie is added via store.putCookie(...) in the order in which they appear in the serialization.

    Parameter strOrObj

    A JSON string or object representing the deserialized cookies.

    Parameter callback

    A function to call after the CookieJar has been deserialized.

    Remarks

    - When no Store is provided, a new MemoryCookieStore will be used.

    - As a convenience, if strOrObj is a string, it is passed through JSON.parse first.

  • A new CookieJar is created and the serialized Cookie values are added to the underlying store. Each Cookie is added via store.putCookie(...) in the order in which they appear in the serialization.

    Parameter strOrObj

    A JSON string or object representing the deserialized cookies.

    Parameter store

    The underlying store to persist the deserialized cookies into.

    Parameter callback

    A function to call after the CookieJar has been deserialized.

    Remarks

    - When no Store is provided, a new MemoryCookieStore will be used.

    - As a convenience, if strOrObj is a string, it is passed through JSON.parse first.

  • A new CookieJar is created and the serialized Cookie values are added to the underlying store. Each Cookie is added via store.putCookie(...) in the order in which they appear in the serialization.

    Parameter strOrObj

    A JSON string or object representing the deserialized cookies.

    Parameter store

    The underlying store to persist the deserialized cookies into.

    Remarks

    - When no Store is provided, a new MemoryCookieStore will be used.

    - As a convenience, if strOrObj is a string, it is passed through JSON.parse first.

  • No doc because this is an overload that supports the implementation

    Modifiers

    • @internal

method deserializeSync

static deserializeSync: (
strOrObj: string | SerializedCookieJar,
store?: Store
) => CookieJar;
  • A new CookieJar is created and the serialized Cookie values are added to the underlying store. Each Cookie is added via store.putCookie(...) in the order in which they appear in the serialization.

    Note: Only works if the configured Store is also synchronous.

    Parameter strOrObj

    A JSON string or object representing the deserialized cookies.

    Parameter store

    The underlying store to persist the deserialized cookies into.

    Remarks

    - When no Store is provided, a new MemoryCookieStore will be used.

    - As a convenience, if strOrObj is a string, it is passed through JSON.parse first.

method fromJSON

static fromJSON: (
jsonString: string | SerializedCookieJar,
store?: Store
) => CookieJar;
  • Alias of CookieJar.deserializeSync.

    Parameter jsonString

    A JSON string or object representing the deserialized cookies.

    Parameter store

    The underlying store to persist the deserialized cookies into.

    Remarks

    - When no Store is provided, a new MemoryCookieStore will be used.

    - As a convenience, if strOrObj is a string, it is passed through JSON.parse first.

method getCookies

getCookies: {
(url: string): Promise<Cookie[]>;
(url: string, callback: Callback<Cookie[]>): void;
(
url: string | URL,
options: GetCookiesOptions,
callback: Callback<Cookie[]>
): void;
(url: string | URL, options?: GetCookiesOptions): Promise<Cookie[]>;
(
url: string | URL,
options: Callback<Cookie[]> | GetCookiesOptions,
callback?: Callback<Cookie[]>
): unknown;
};
  • Retrieve the list of cookies that can be sent in a Cookie header for the current URL.

    Parameter url

    The domain to store the cookie with.

    Remarks

    - The array of cookies returned will be sorted according to cookieCompare.

    - The Cookie.lastAccessed property will be updated on all returned cookies.

  • Retrieve the list of cookies that can be sent in a Cookie header for the current URL.

    Parameter url

    The domain to store the cookie with.

    Parameter callback

    A function to call after a cookie has been successfully retrieved.

    Remarks

    - The array of cookies returned will be sorted according to cookieCompare.

    - The Cookie.lastAccessed property will be updated on all returned cookies.

  • Retrieve the list of cookies that can be sent in a Cookie header for the current URL.

    Parameter url

    The domain to store the cookie with.

    Parameter options

    Configuration settings to use when retrieving the cookies.

    Parameter callback

    A function to call after a cookie has been successfully retrieved.

    Remarks

    - The array of cookies returned will be sorted according to cookieCompare.

    - The Cookie.lastAccessed property will be updated on all returned cookies.

  • Retrieve the list of cookies that can be sent in a Cookie header for the current URL.

    Parameter url

    The domain to store the cookie with.

    Parameter options

    Configuration settings to use when retrieving the cookies.

    Remarks

    - The array of cookies returned will be sorted according to cookieCompare.

    - The Cookie.lastAccessed property will be updated on all returned cookies.

  • No doc because this is an overload that supports the implementation

    Modifiers

    • @internal

method getCookiesSync

getCookiesSync: (url: string, options?: GetCookiesOptions) => Cookie[];
  • Synchronously retrieve the list of cookies that can be sent in a Cookie header for the current URL.

    Note: Only works if the configured Store is also synchronous.

    Parameter url

    The domain to store the cookie with.

    Parameter options

    Configuration settings to use when retrieving the cookies.

    Remarks

    - The array of cookies returned will be sorted according to cookieCompare.

    - The Cookie.lastAccessed property will be updated on all returned cookies.

method getCookieString

getCookieString: {
(
url: string,
options: GetCookiesOptions,
callback: Callback<string | undefined>
): void;
(url: string, callback: Callback<string>): void;
(url: string, options?: GetCookiesOptions): Promise<string>;
(
url: string,
options: GetCookiesOptions | Callback<string>,
callback?: Callback<string>
): unknown;
};
  • Accepts the same options as .getCookies() but returns a string suitable for a Cookie header rather than an Array.

    Parameter url

    The domain to store the cookie with.

    Parameter options

    Configuration settings to use when retrieving the cookies.

    Parameter callback

    A function to call after the Cookie header string has been created.

  • Accepts the same options as .getCookies() but returns a string suitable for a Cookie header rather than an Array.

    Parameter url

    The domain to store the cookie with.

    Parameter callback

    A function to call after the Cookie header string has been created.

  • Accepts the same options as .getCookies() but returns a string suitable for a Cookie header rather than an Array.

    Parameter url

    The domain to store the cookie with.

    Parameter options

    Configuration settings to use when retrieving the cookies.

  • No doc because this is an overload that supports the implementation

    Modifiers

    • @internal

method getCookieStringSync

getCookieStringSync: (url: string, options?: GetCookiesOptions) => string;
  • Synchronous version of .getCookieString(). Accepts the same options as .getCookies() but returns a string suitable for a Cookie header rather than an Array.

    Note: Only works if the configured Store is also synchronous.

    Parameter url

    The domain to store the cookie with.

    Parameter options

    Configuration settings to use when retrieving the cookies.

method getSetCookieStrings

getSetCookieStrings: {
(url: string, callback: Callback<string[] | undefined>): void;
(
url: string,
options: GetCookiesOptions,
callback: Callback<string[]>
): void;
(url: string, options?: GetCookiesOptions): Promise<string[]>;
(
url: string,
options: GetCookiesOptions,
callback?: Callback<string[]>
): unknown;
};
  • Returns an array of strings suitable for Set-Cookie headers. Accepts the same options as .getCookies().

    Parameter url

    The domain to store the cookie with.

    Parameter callback

    A function to call after the Set-Cookie header strings have been created.

  • Returns an array of strings suitable for Set-Cookie headers. Accepts the same options as .getCookies().

    Parameter url

    The domain to store the cookie with.

    Parameter options

    Configuration settings to use when retrieving the cookies.

    Parameter callback

    A function to call after the Set-Cookie header strings have been created.

  • Returns an array of strings suitable for Set-Cookie headers. Accepts the same options as .getCookies().

    Parameter url

    The domain to store the cookie with.

    Parameter options

    Configuration settings to use when retrieving the cookies.

  • No doc because this is an overload that supports the implementation

    Modifiers

    • @internal

method getSetCookieStringsSync

getSetCookieStringsSync: (url: string, options?: GetCookiesOptions) => string[];
  • Synchronous version of .getSetCookieStrings(). Returns an array of strings suitable for Set-Cookie headers. Accepts the same options as .getCookies().

    Note: Only works if the configured Store is also synchronous.

    Parameter url

    The domain to store the cookie with.

    Parameter options

    Configuration settings to use when retrieving the cookies.

method removeAllCookies

removeAllCookies: { (callback: ErrorCallback): void; (): Promise<void> };
  • Removes all cookies from the CookieJar.

    Parameter callback

    A function to call when all the cookies have been removed.

    Remarks

    - This is a new backwards-compatible feature of tough-cookie version 2.5, so not all Stores will implement it efficiently. For Stores that do not implement removeAllCookies, the fallback is to call removeCookie after getAllCookies.

    - If getAllCookies fails or isn't implemented in the Store, an error is returned.

    - If one or more of the removeCookie calls fail, only the first error is returned.

  • Removes all cookies from the CookieJar.

    Remarks

    - This is a new backwards-compatible feature of tough-cookie version 2.5, so not all Stores will implement it efficiently. For Stores that do not implement removeAllCookies, the fallback is to call removeCookie after getAllCookies.

    - If getAllCookies fails or isn't implemented in the Store, an error is returned.

    - If one or more of the removeCookie calls fail, only the first error is returned.

method removeAllCookiesSync

removeAllCookiesSync: () => void;
  • Removes all cookies from the CookieJar.

    Note: Only works if the configured Store is also synchronous.

    Remarks

    - This is a new backwards-compatible feature of tough-cookie version 2.5, so not all Stores will implement it efficiently. For Stores that do not implement removeAllCookies, the fallback is to call removeCookie after getAllCookies.

    - If getAllCookies fails or isn't implemented in the Store, an error is returned.

    - If one or more of the removeCookie calls fail, only the first error is returned.

method serialize

serialize: {
(callback: Callback<SerializedCookieJar>): void;
(): Promise<SerializedCookieJar>;
};
  • Serialize the CookieJar if the underlying store supports .getAllCookies.

    Parameter callback

    A function to call after the CookieJar has been serialized

  • Serialize the CookieJar if the underlying store supports .getAllCookies.

method serializeSync

serializeSync: () => SerializedCookieJar | undefined;
  • Serialize the CookieJar if the underlying store supports .getAllCookies.

    Note: Only works if the configured Store is also synchronous.

method setCookie

setCookie: {
(
cookie: string | Cookie,
url: string | URL,
callback: Callback<Cookie | undefined>
): void;
(
cookie: string | Cookie,
url: string | URL,
options: SetCookieOptions,
callback: Callback<Cookie>
): void;
(
cookie: string | Cookie,
url: string | URL,
options?: SetCookieOptions
): Promise<Cookie>;
(
cookie: string | Cookie,
url: string | URL,
options: Callback<Cookie> | SetCookieOptions,
callback?: Callback<Cookie>
): unknown;
};
  • Attempt to set the Cookie in the CookieJar.

    Parameter cookie

    The cookie object or cookie string to store. A string value will be parsed into a cookie using Cookie.parse.

    Parameter url

    The domain to store the cookie with.

    Parameter callback

    A function to call after a cookie has been successfully stored.

    Remarks

    - If successfully persisted, the Cookie will have updated Cookie.creation, Cookie.lastAccessed and Cookie.hostOnly properties.

    - As per the RFC, the Cookie.hostOnly flag is set if there was no Domain={value} atttribute on the cookie string. The Cookie.domain property is set to the fully-qualified hostname of currentUrl in this case. Matching this cookie requires an exact hostname match (not a domainMatch as per usual)

    Modifiers

    • @public
  • Attempt to set the Cookie in the CookieJar.

    Parameter cookie

    The cookie object or cookie string to store. A string value will be parsed into a cookie using Cookie.parse.

    Parameter url

    The domain to store the cookie with.

    Parameter options

    Configuration settings to use when storing the cookie.

    Parameter callback

    A function to call after a cookie has been successfully stored.

    Remarks

    - If successfully persisted, the Cookie will have updated Cookie.creation, Cookie.lastAccessed and Cookie.hostOnly properties.

    - As per the RFC, the Cookie.hostOnly flag is set if there was no Domain={value} atttribute on the cookie string. The Cookie.domain property is set to the fully-qualified hostname of currentUrl in this case. Matching this cookie requires an exact hostname match (not a domainMatch as per usual)

    Modifiers

    • @public
  • Attempt to set the Cookie in the CookieJar.

    Parameter cookie

    The cookie object or cookie string to store. A string value will be parsed into a cookie using Cookie.parse.

    Parameter url

    The domain to store the cookie with.

    Parameter options

    Configuration settings to use when storing the cookie.

    Remarks

    - If successfully persisted, the Cookie will have updated Cookie.creation, Cookie.lastAccessed and Cookie.hostOnly properties.

    - As per the RFC, the Cookie.hostOnly flag is set if there was no Domain={value} atttribute on the cookie string. The Cookie.domain property is set to the fully-qualified hostname of currentUrl in this case. Matching this cookie requires an exact hostname match (not a domainMatch as per usual)

    Modifiers

    • @public
  • No doc because this is an overload that supports the implementation

    Modifiers

    • @internal

method setCookieSync

setCookieSync: (
cookie: string | Cookie,
url: string,
options?: SetCookieOptions
) => Cookie | undefined;
  • Synchronously attempt to set the Cookie in the CookieJar.

    Note: Only works if the configured Store is also synchronous.

    Parameter cookie

    The cookie object or cookie string to store. A string value will be parsed into a cookie using Cookie.parse.

    Parameter url

    The domain to store the cookie with.

    Parameter options

    Configuration settings to use when storing the cookie.

    Remarks

    - If successfully persisted, the Cookie will have updated Cookie.creation, Cookie.lastAccessed and Cookie.hostOnly properties.

    - As per the RFC, the Cookie.hostOnly flag is set if there was no Domain={value} atttribute on the cookie string. The Cookie.domain property is set to the fully-qualified hostname of currentUrl in this case. Matching this cookie requires an exact hostname match (not a domainMatch as per usual)

    Modifiers

    • @public

method toJSON

toJSON: () => SerializedCookieJar | undefined;

class MemoryCookieStore

class MemoryCookieStore extends Store {}
  • An in-memory Store implementation for CookieJar. This is the default implementation used by CookieJar and supports both async and sync operations. Also supports serialization, getAllCookies, and removeAllCookies.

    Modifiers

    • @public

constructor

constructor();

property synchronous

synchronous: boolean;

method findCookie

findCookie: {
(
domain: Nullable<string>,
path: Nullable<string>,
key: Nullable<string>
): Promise<Cookie | undefined>;
(
domain: string,
path: string,
key: string,
callback: Callback<Cookie>
): void;
};
  • Retrieve a Cookie with the given domain, path, and key (name). The RFC maintains that exactly one of these cookies should exist in a store. If the store is using versioning, this means that the latest or newest such cookie should be returned.

    Parameter domain

    The cookie domain to match against.

    Parameter path

    The cookie path to match against.

    Parameter key

    The cookie name to match against.

  • Retrieve a Cookie with the given domain, path, and key (name). The RFC maintains that exactly one of these cookies should exist in a store. If the store is using versioning, this means that the latest or newest such cookie should be returned.

    Callback takes an error and the resulting Cookie object. If no cookie is found then null MUST be passed instead (that is, not an error).

    Parameter domain

    The cookie domain to match against.

    Parameter path

    The cookie path to match against.

    Parameter key

    The cookie name to match against.

    Parameter callback

    A function to call with either the found cookie or an error.

method findCookies

findCookies: {
(domain: string, path: string, allowSpecialUseDomain?: boolean): Promise<
Cookie[]
>;
(
domain: string,
path: string,
allowSpecialUseDomain?: boolean,
callback?: Callback<Cookie[]>
): void;
};
  • Locates all Cookie values matching the given domain and path.

    The resulting list is checked for applicability to the current request according to the RFC (domain-match, path-match, http-only-flag, secure-flag, expiry, and so on), so it's OK to use an optimistic search algorithm when implementing this method. However, the search algorithm used SHOULD try to find cookies that domainMatch the domain and pathMatch the path in order to limit the amount of checking that needs to be done.

    Parameter domain

    The cookie domain to match against.

    Parameter path

    The cookie path to match against.

    Parameter allowSpecialUseDomain

    If true then special-use domain suffixes, will be allowed in matches. Defaults to false.

    Remarks

    - As of version 0.9.12, the allPaths option to cookiejar.getCookies() above causes the path here to be null.

    - If the path is null, path-matching MUST NOT be performed (that is, domain-matching only).

  • Locates all Cookie values matching the given domain and path.

    The resulting list is checked for applicability to the current request according to the RFC (domain-match, path-match, http-only-flag, secure-flag, expiry, and so on), so it's OK to use an optimistic search algorithm when implementing this method. However, the search algorithm used SHOULD try to find cookies that domainMatch the domain and pathMatch the path in order to limit the amount of checking that needs to be done.

    Parameter domain

    The cookie domain to match against.

    Parameter path

    The cookie path to match against.

    Parameter allowSpecialUseDomain

    If true then special-use domain suffixes, will be allowed in matches. Defaults to false.

    Parameter callback

    A function to call with either the found cookies or an error.

    Remarks

    - As of version 0.9.12, the allPaths option to cookiejar.getCookies() above causes the path here to be null.

    - If the path is null, path-matching MUST NOT be performed (that is, domain-matching only).

method getAllCookies

getAllCookies: { (): Promise<Cookie[]>; (callback: Callback<Cookie[]>): void };
  • Gets all the cookies in the store.

    Remarks

    - Cookies SHOULD be returned in creation order to preserve sorting via cookieCompare.

  • Gets all the cookies in the store.

    Parameter callback

    A function to call when all the cookies have been retrieved or an error occurs.

    Remarks

    - Cookies SHOULD be returned in creation order to preserve sorting via cookieCompare.

method putCookie

putCookie: {
(cookie: Cookie): Promise<void>;
(cookie: Cookie, callback: ErrorCallback): void;
};
  • Adds a new Cookie to the store. The implementation SHOULD replace any existing cookie with the same domain, path, and key properties.

    Parameter cookie

    The cookie to store.

    Remarks

    - Depending on the nature of the implementation, it's possible that between the call to fetchCookie and putCookie that a duplicate putCookie can occur.

    - The Cookie object MUST NOT be modified; as the caller has already updated the creation and lastAccessed properties.

  • Adds a new Cookie to the store. The implementation SHOULD replace any existing cookie with the same domain, path, and key properties.

    Parameter cookie

    The cookie to store.

    Parameter callback

    A function to call when the cookie has been stored or an error has occurred.

    Remarks

    - Depending on the nature of the implementation, it's possible that between the call to fetchCookie and putCookie that a duplicate putCookie can occur.

    - The Cookie object MUST NOT be modified; as the caller has already updated the creation and lastAccessed properties.

method removeAllCookies

removeAllCookies: { (): Promise<void>; (callback: ErrorCallback): void };
  • Removes all cookies from the store.

  • Removes all cookies from the store.

    Parameter callback

    A function to call when all the cookies have been removed or an error occurs.

method removeCookie

removeCookie: {
(domain: string, path: string, key: string): Promise<void>;
(domain: string, path: string, key: string, callback: ErrorCallback): void;
};
  • Remove a cookie from the store (see notes on findCookie about the uniqueness constraint).

    Parameter domain

    The cookie domain to match against.

    Parameter path

    The cookie path to match against.

    Parameter key

    The cookie name to match against.

  • Remove a cookie from the store (see notes on findCookie about the uniqueness constraint).

    Parameter domain

    The cookie domain to match against.

    Parameter path

    The cookie path to match against.

    Parameter key

    The cookie name to match against.

    Parameter callback

    A function to call when the cookie has been removed or an error occurs.

method removeCookies

removeCookies: {
(domain: string, path: string): Promise<void>;
(domain: string, path: string, callback: ErrorCallback): void;
};
  • Removes matching cookies from the store. The path parameter is optional and if missing, means all paths in a domain should be removed.

    Parameter domain

    The cookie domain to match against.

    Parameter path

    The cookie path to match against.

  • Removes matching cookies from the store. The path parameter is optional and if missing, means all paths in a domain should be removed.

    Parameter domain

    The cookie domain to match against.

    Parameter path

    The cookie path to match against.

    Parameter callback

    A function to call when the cookies have been removed or an error occurs.

method updateCookie

updateCookie: {
(oldCookie: Cookie, newCookie: Cookie): Promise<void>;
(oldCookie: Cookie, newCookie: Cookie, callback: ErrorCallback): void;
};
  • Update an existing Cookie. The implementation MUST update the value for a cookie with the same domain, path, and key. The implementation SHOULD check that the old value in the store is equivalent to oldCookie - how the conflict is resolved is up to the store.

    Parameter oldCookie

    the cookie that is already present in the store.

    Parameter newCookie

    the cookie to replace the one already present in the store.

    Remarks

    - The lastAccessed property is always different between the two objects (to the precision possible via JavaScript's clock).

    - Both creation and creationIndex are guaranteed to be the same.

    - Stores MAY ignore or defer the lastAccessed change at the cost of affecting how cookies are selected for automatic deletion.

    - Stores may wish to optimize changing the value of the cookie in the store versus storing a new cookie.

    - The newCookie and oldCookie objects MUST NOT be modified.

  • Update an existing Cookie. The implementation MUST update the value for a cookie with the same domain, path, and key. The implementation SHOULD check that the old value in the store is equivalent to oldCookie - how the conflict is resolved is up to the store.

    Parameter oldCookie

    the cookie that is already present in the store.

    Parameter newCookie

    the cookie to replace the one already present in the store.

    Parameter callback

    A function to call when the cookie has been updated or an error has occurred.

    Remarks

    - The lastAccessed property is always different between the two objects (to the precision possible via JavaScript's clock).

    - Both creation and creationIndex are guaranteed to be the same.

    - Stores MAY ignore or defer the lastAccessed change at the cost of affecting how cookies are selected for automatic deletion.

    - Stores may wish to optimize changing the value of the cookie in the store versus storing a new cookie.

    - The newCookie and oldCookie objects MUST NOT be modified.

class ParameterError

class ParameterError extends Error {}
  • Represents a validation error.

    Modifiers

    • @public

class Store

class Store {}
  • Base class for CookieJar stores.

    The storage model for each CookieJar instance can be replaced with a custom implementation. The default is MemoryCookieStore.

    Remarks

    - Stores should inherit from the base Store class, which is available as a top-level export.

    - Stores are asynchronous by default, but if Store.synchronous is set to true, then the *Sync methods of the containing CookieJar can be used.

    Modifiers

    • @public

constructor

constructor();

    property synchronous

    synchronous: boolean;
    • Store implementations that support synchronous methods must return true.

    method findCookie

    findCookie: {
    (
    domain: Nullable<string>,
    path: Nullable<string>,
    key: Nullable<string>
    ): Promise<Cookie | undefined>;
    (
    domain: string,
    path: string,
    key: string,
    callback: Callback<Cookie>
    ): void;
    };
    • Retrieve a Cookie with the given domain, path, and key (name). The RFC maintains that exactly one of these cookies should exist in a store. If the store is using versioning, this means that the latest or newest such cookie should be returned.

      Callback takes an error and the resulting Cookie object. If no cookie is found then null MUST be passed instead (that is, not an error).

      Parameter domain

      The cookie domain to match against.

      Parameter path

      The cookie path to match against.

      Parameter key

      The cookie name to match against.

    • Retrieve a Cookie with the given domain, path, and key (name). The RFC maintains that exactly one of these cookies should exist in a store. If the store is using versioning, this means that the latest or newest such cookie should be returned.

      Callback takes an error and the resulting Cookie object. If no cookie is found then null MUST be passed instead (that is, not an error).

      Parameter domain

      The cookie domain to match against.

      Parameter path

      The cookie path to match against.

      Parameter key

      The cookie name to match against.

      Parameter callback

      A function to call with either the found cookie or an error.

    method findCookies

    findCookies: {
    (
    domain: Nullable<string>,
    path: Nullable<string>,
    allowSpecialUseDomain?: boolean
    ): Promise<Cookie[]>;
    (
    domain: string,
    path: string,
    allowSpecialUseDomain?: boolean,
    callback?: Callback<Cookie[]>
    ): void;
    };
    • Locates all Cookie values matching the given domain and path.

      The resulting list is checked for applicability to the current request according to the RFC (domain-match, path-match, http-only-flag, secure-flag, expiry, and so on), so it's OK to use an optimistic search algorithm when implementing this method. However, the search algorithm used SHOULD try to find cookies that domainMatch the domain and pathMatch the path in order to limit the amount of checking that needs to be done.

      Parameter domain

      The cookie domain to match against.

      Parameter path

      The cookie path to match against.

      Parameter allowSpecialUseDomain

      If true then special-use domain suffixes, will be allowed in matches. Defaults to false.

      Remarks

      - As of version 0.9.12, the allPaths option to cookiejar.getCookies() above causes the path here to be null.

      - If the path is null, path-matching MUST NOT be performed (that is, domain-matching only).

    • Locates all Cookie values matching the given domain and path.

      The resulting list is checked for applicability to the current request according to the RFC (domain-match, path-match, http-only-flag, secure-flag, expiry, and so on), so it's OK to use an optimistic search algorithm when implementing this method. However, the search algorithm used SHOULD try to find cookies that domainMatch the domain and pathMatch the path in order to limit the amount of checking that needs to be done.

      Parameter domain

      The cookie domain to match against.

      Parameter path

      The cookie path to match against.

      Parameter allowSpecialUseDomain

      If true then special-use domain suffixes, will be allowed in matches. Defaults to false.

      Parameter callback

      A function to call with either the found cookies or an error.

      Remarks

      - As of version 0.9.12, the allPaths option to cookiejar.getCookies() above causes the path here to be null.

      - If the path is null, path-matching MUST NOT be performed (that is, domain-matching only).

    method getAllCookies

    getAllCookies: { (): Promise<Cookie[]>; (callback: Callback<Cookie[]>): void };
    • Gets all the cookies in the store.

      Remarks

      - Cookies SHOULD be returned in creation order to preserve sorting via cookieCompare.

    • Gets all the cookies in the store.

      Parameter callback

      A function to call when all the cookies have been retrieved or an error occurs.

      Remarks

      - Cookies SHOULD be returned in creation order to preserve sorting via cookieCompare.

    method putCookie

    putCookie: {
    (cookie: Cookie): Promise<void>;
    (cookie: Cookie, callback: ErrorCallback): void;
    };
    • Adds a new Cookie to the store. The implementation SHOULD replace any existing cookie with the same domain, path, and key properties.

      Parameter cookie

      The cookie to store.

      Remarks

      - Depending on the nature of the implementation, it's possible that between the call to fetchCookie and putCookie that a duplicate putCookie can occur.

      - The Cookie object MUST NOT be modified; as the caller has already updated the creation and lastAccessed properties.

    • Adds a new Cookie to the store. The implementation SHOULD replace any existing cookie with the same domain, path, and key properties.

      Parameter cookie

      The cookie to store.

      Parameter callback

      A function to call when the cookie has been stored or an error has occurred.

      Remarks

      - Depending on the nature of the implementation, it's possible that between the call to fetchCookie and putCookie that a duplicate putCookie can occur.

      - The Cookie object MUST NOT be modified; as the caller has already updated the creation and lastAccessed properties.

    method removeAllCookies

    removeAllCookies: { (): Promise<void>; (callback: ErrorCallback): void };
    • Removes all cookies from the store.

    • Removes all cookies from the store.

      Parameter callback

      A function to call when all the cookies have been removed or an error occurs.

    method removeCookie

    removeCookie: {
    (
    domain: Nullable<string>,
    path: Nullable<string>,
    key: Nullable<string>
    ): Promise<void>;
    (domain: string, path: string, key: string, callback: ErrorCallback): void;
    };
    • Remove a cookie from the store (see notes on findCookie about the uniqueness constraint).

      Parameter domain

      The cookie domain to match against.

      Parameter path

      The cookie path to match against.

      Parameter key

      The cookie name to match against.

    • Remove a cookie from the store (see notes on findCookie about the uniqueness constraint).

      Parameter domain

      The cookie domain to match against.

      Parameter path

      The cookie path to match against.

      Parameter key

      The cookie name to match against.

      Parameter callback

      A function to call when the cookie has been removed or an error occurs.

    method removeCookies

    removeCookies: {
    (domain: string, path: Nullable<string>): Promise<void>;
    (domain: string, path: string, callback: ErrorCallback): void;
    };
    • Removes matching cookies from the store. The path parameter is optional and if missing, means all paths in a domain should be removed.

      Parameter domain

      The cookie domain to match against.

      Parameter path

      The cookie path to match against.

    • Removes matching cookies from the store. The path parameter is optional and if missing, means all paths in a domain should be removed.

      Parameter domain

      The cookie domain to match against.

      Parameter path

      The cookie path to match against.

      Parameter callback

      A function to call when the cookies have been removed or an error occurs.

    method updateCookie

    updateCookie: {
    (oldCookie: Cookie, newCookie: Cookie): Promise<void>;
    (oldCookie: Cookie, newCookie: Cookie, callback: ErrorCallback): void;
    };
    • Update an existing Cookie. The implementation MUST update the value for a cookie with the same domain, path, and key. The implementation SHOULD check that the old value in the store is equivalent to oldCookie - how the conflict is resolved is up to the store.

      Parameter oldCookie

      the cookie that is already present in the store.

      Parameter newCookie

      the cookie to replace the one already present in the store.

      Remarks

      - The lastAccessed property is always different between the two objects (to the precision possible via JavaScript's clock).

      - Both creation and creationIndex are guaranteed to be the same.

      - Stores MAY ignore or defer the lastAccessed change at the cost of affecting how cookies are selected for automatic deletion.

      - Stores may wish to optimize changing the value of the cookie in the store versus storing a new cookie.

      - The newCookie and oldCookie objects MUST NOT be modified.

    • Update an existing Cookie. The implementation MUST update the value for a cookie with the same domain, path, and key. The implementation SHOULD check that the old value in the store is equivalent to oldCookie - how the conflict is resolved is up to the store.

      Parameter oldCookie

      the cookie that is already present in the store.

      Parameter newCookie

      the cookie to replace the one already present in the store.

      Parameter callback

      A function to call when the cookie has been updated or an error has occurred.

      Remarks

      - The lastAccessed property is always different between the two objects (to the precision possible via JavaScript's clock).

      - Both creation and creationIndex are guaranteed to be the same.

      - Stores MAY ignore or defer the lastAccessed change at the cost of affecting how cookies are selected for automatic deletion.

      - Stores may wish to optimize changing the value of the cookie in the store versus storing a new cookie.

      - The newCookie and oldCookie objects MUST NOT be modified.

    Interfaces

    interface Callback

    interface Callback<T> {}
    • A callback function that accepts an error or a result.

      Modifiers

      • @public

    call signature

    (error: Error, result?: never): void;

      call signature

      (error: null, result: T): void;

        interface CreateCookieJarOptions

        interface CreateCookieJarOptions {}
        • Configuration settings to be used with a CookieJar.

          Modifiers

          • @public

        property allowSpecialUseDomain

        allowSpecialUseDomain?: boolean | undefined;
        • Accepts special-use domains such as local. This is not in the standard, but is used sometimes on the web and is accepted by most browsers. It is also useful for testing purposes.

          Defaults to true if not specified.

        property looseMode

        looseMode?: boolean | undefined;
        • Accept malformed cookies like bar and =bar, which have an implied empty name but are not RFC-compliant.

          Defaults to false if not specified.

        property prefixSecurity

        prefixSecurity?: 'strict' | 'silent' | 'unsafe-disabled' | undefined;
        • Controls how cookie prefixes are handled. See PrefixSecurityEnum.

          Defaults to silent if not specified.

        property rejectPublicSuffixes

        rejectPublicSuffixes?: boolean | undefined;
        • Reject cookies that match those defined in the Public Suffix List (e.g.; domains like "com" and "co.uk").

          Defaults to true if not specified.

        interface CreateCookieOptions

        interface CreateCookieOptions {}
        • Configurable values that can be set when creating a Cookie.

          Modifiers

          • @public

        property creation

        creation?: Date | 'Infinity' | null;

        property domain

        domain?: string | null;

        property expires

        expires?: Date | 'Infinity' | null;

        property extensions

        extensions?: string[] | null;

        property hostOnly

        hostOnly?: boolean | null;

        property httpOnly

        httpOnly?: boolean;

        property key

        key?: string;

        property lastAccessed

        lastAccessed?: Date | 'Infinity' | null;

        property maxAge

        maxAge?: number | 'Infinity' | '-Infinity' | null;

        property path

        path?: string | null;

        property pathIsDefault

        pathIsDefault?: boolean | null;

        property sameSite

        sameSite?: string | undefined;

        property secure

        secure?: boolean;

        property value

        value?: string;

        interface ErrorCallback

        interface ErrorCallback {}
        • A callback function that only accepts an error.

          Modifiers

          • @public

        call signature

        (error: Error | null): void;

          interface GetCookiesOptions

          interface GetCookiesOptions {}
          • Configuration options used when calling CookieJar.getCookies(...).

            Modifiers

            • @public

          property allPaths

          allPaths?: boolean | undefined;
          • If true, do not scope cookies by path. If false, then RFC-compliant path scoping will be used.

            Remarks

            - May not be supported by the underlying store (the default MemoryCookieStore supports it).

            Defaults to false if not provided.

          property expire

          expire?: boolean | undefined;
          • Perform expiry-time checking of cookies and asynchronously remove expired cookies from the store.

            Remarks

            - Using false returns expired cookies and does not remove them from the store which is potentially useful for replaying Set-Cookie headers.

            Defaults to true if not provided.

          property http

          http?: boolean | undefined;
          • Indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies.

            Defaults to true if not provided.

          property sameSiteContext

          sameSiteContext?: 'none' | 'lax' | 'strict' | undefined;
          • Set this to 'none', 'lax', or 'strict' to enforce SameSite cookies upon retrieval.

            - 'strict' - If the request is on the same "site for cookies" (see the RFC draft for more information), pass this option to add a layer of defense against CSRF.

            - 'lax' - If the request is from another site, but is directly because of navigation by the user, such as, <link type=prefetch> or <a href="...">, then use lax.

            - 'none' - This indicates a cross-origin request.

            - undefined - SameSite is not be enforced! This can be a valid use-case for when CSRF isn't in the threat model of the system being built.

            Defaults to undefined if not provided.

            Remarks

            - It is highly recommended that you read RFC6265bis - Section 8.8 which discusses security considerations and defence on SameSite cookies in depth.

          property sort

          sort?: boolean | undefined;
          • Flag to indicate if the returned cookies should be sorted or not.

            Defaults to undefined if not provided.

          interface GetPublicSuffixOptions

          interface GetPublicSuffixOptions {}

          property allowSpecialUseDomain

          allowSpecialUseDomain?: boolean | undefined;
          • If set to true then the following Special Use Domains will be treated as if they were valid public suffixes ('local', 'example', 'invalid', 'localhost', 'test').

            Remarks

            In testing scenarios it's common to configure the cookie store with so that http://localhost can be used as a domain:

            {
            allowSpecialUseDomain: true,
            rejectPublicSuffixes: false
            }

          property ignoreError

          ignoreError?: boolean | undefined;
          • If set to true then any errors that occur while executing getPublicSuffix will be silently ignored.

          interface ParseCookieOptions

          interface ParseCookieOptions {}
          • Optional configuration to be used when parsing cookies.

            Modifiers

            • @public

          property loose

          loose?: boolean | undefined;
          • If true then keyless cookies like =abc and = which are not RFC-compliant will be parsed.

          interface SerializedCookieJar

          interface SerializedCookieJar {}
          • A JSON representation of a CookieJar.

            Modifiers

            • @public

          property cookies

          cookies: SerializedCookie[];
          • The list of Cookie values serialized as JSON objects.

          property rejectPublicSuffixes

          rejectPublicSuffixes: boolean;

          property storeType

          storeType: string | null;
          • The name of the store used during serialization.

          property version

          version: string;
          • The version of tough-cookie used during serialization.

          index signature

          [key: string]: unknown;
          • Other configuration settings on the CookieJar.

          interface SetCookieOptions

          interface SetCookieOptions {}
          • Configuration options used when calling CookieJar.setCookie(...)

            Modifiers

            • @public

          property http

          http?: boolean | undefined;
          • Indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies.

            Defaults to true if not provided.

          property ignoreError

          ignoreError?: boolean | undefined;
          • Silently ignore things like parse errors and invalid domains. Store errors aren't ignored by this option.

            Defaults to false if not provided.

          property loose

          loose?: boolean | undefined;
          • Controls if a cookie string should be parsed using loose mode or not. See Cookie.parse and ParseCookieOptions for more details.

            Defaults to false if not provided.

          property now

          now?: Date | undefined;
          • Forces the cookie creation and access time of cookies to this value when stored.

            Defaults to Date.now() if not provided.

          property sameSiteContext

          sameSiteContext?: 'strict' | 'lax' | 'none' | undefined;
          • Set this to 'none', 'lax', or 'strict' to enforce SameSite cookies upon storage.

            - 'strict' - If the request is on the same "site for cookies" (see the RFC draft for more information), pass this option to add a layer of defense against CSRF.

            - 'lax' - If the request is from another site, but is directly because of navigation by the user, such as, <link type=prefetch> or <a href="...">, then use lax.

            - 'none' - This indicates a cross-origin request.

            - undefined - SameSite is not be enforced! This can be a valid use-case for when CSRF isn't in the threat model of the system being built.

            Defaults to undefined if not provided.

            Remarks

            - It is highly recommended that you read RFC6265bis - Section 8.8 which discusses security considerations and defence on SameSite cookies in depth.

          Type Aliases

          type Nullable

          type Nullable<T> = T | null | undefined;
          • The inverse of NonNullable.

            Modifiers

            • @public

          type SerializedCookie

          type SerializedCookie = {
          key?: string;
          value?: string;
          [key: string]: unknown;
          };

          Package Files (19)

          Dependencies (1)

          Dev Dependencies (18)

          Peer Dependencies (0)

          No peer dependencies.

          Badge

          To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

          You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/tough-cookie.

          • Markdown
            [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/tough-cookie)
          • HTML
            <a href="https://www.jsdocs.io/package/tough-cookie"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>