Cookies API

cookie.set()

Sets a cookie associated with the current document using the passed name and value.

  • Accepts the cookie name as a string as the first argument.
    Accepts the cookie value as the second argument, which can be a string, number, object, array, boolean (true or false), or null.
    Accepts an optional third argument as an object with the following options:
    Option
    Type
    Description
    path
    string
    Overridden by "/" if "prefixHost" is true.
    domain
    string
    Ignored if "prefixHost" is true.
    age
    number
    Maximum age in seconds takes precedence over "expires".
    expires
    date
    number
    string
    Number of days - will automatically calculate the date, Date object, ISO 8601, or RFC 1123.
    secure
    boolean
    Indicates whether the cookie should only be transmitted over secure protocols such as HTTPS.
    No matter the value passed, it becomes true if "prefixSecure" or "prefixHost" is true.
    same
    'strict'
    'lax'
    The "strict" value prevents the cookie from being sent in all cross-site contexts, while "lax" sends cookies only for top-level navigation GET requests, sufficient for user tracking but limiting CSRF attacks.
    prefixSecure
    boolean
    Indicates to the browser to include the cookie only in requests over a secure channel.
    Takes precedence over "prefixHost".
    prefixHost
    boolean
    Signals to the browser that the cookie is restricted to a secure origin and limited to a specified "path".
    If the path is omitted, the request URI's directory is used.
    The "domain" option must not be present to prevent sending the cookie to other domains.
    All options are optional.
Example:
cookie.set('book', 'cat');
// Sets the cookie 'book' with value 'cat'.

cookie.set('book', {book: 'name', cat: [1, 2]});
// Sets the cookie 'book' with value {book: 'name', cat: [1, 2]}.

cookie.set('book', 10, {
   path: '/',
   domain: 'book.com',
   age: 2592000,
   expires: 'Mon, 20 Oct 2030 07:30:00 GMT',
   secure: true,
   same: 'strict',
   prefixSecure: true,
   prefixHost: false
});
// Sets the cookie 'book' with value 10 based on the provided options.