Cookies

最終更新日:2024-08-14 19:50:30

The Cookies object provides a set of interfaces for manipulating HTTP Cookies. It manages a collection of Cookie objects using name + domain + path as a unique key, and offers functionalities such as adding, retrieving, and removing cookies.

Constructor

const cookies = new Cookies(cookieStr?, isSetCookie?);

Parameters:

Parameter Name Type Required Description
cookieStr string No A cookie string or a Set-Cookie string.
isSetCookie boolean No Indicates whether the cookieStr parameter is a Set-Cookie string. Defaults to false.

Methods

get

cookies.get(name?): null | Cookie | Array<Cookie>;

Retrieves the Cookie object with the specified name. If multiple cookies with the same name exist, it returns an array of Cookie objects.

Parameters:

Parameter Name Type Required Description
name string No The name of the cookie. If omitted, all Cookie objects are returned. If specified, the matching Cookie object or array is returned.

Cookie Object

The Cookie object represents an HTTP Cookie, and its attributes align with those defined in the Set-Cookie HTTP header field. Below is a list of Cookie object attributes. For more details, please refer to the MDN Set-Cookie Documentation:

Attribute Name Type Read-Only Description
name string Yes The name of the cookie.
value string Yes The value of the cookie.
domain string Yes The domain for which the cookie is valid.
path string Yes The path on the server to which the cookie applies.
expires string Yes The expiration date and time of the cookie, adhering to the HTTP Date header standard.
maxAge number Yes The maximum lifetime of the cookie in seconds.
sameSite string Yes Controls the protection mechanism against Cross-Site Request Forgery (CSRF) attacks.
httpOnly boolean Yes Prevents JavaScript access to the cookie, limiting it to HTTP requests only.
secure boolean Yes The cookie is only sent over HTTPS connections.

set

cookies.set(name: string, value: string, options?: Cookie): boolean;

Overwrites or adds a Cookie. It returns true if the addition is successful and false if it fails (e.g., exceeding the cookie quantity limit).

Note: Cookies are overwritten or added using name + domain + path as the unique key.

Parameters:

Parameter Name Type Required Description
name string Yes The name of the cookie.
value string Yes The value of the cookie.
options Cookie No Optional Cookie attribute configuration.

append

cookies.append(name: string, value: string, options?: Cookie): boolean;

Appends a Cookie, suitable for scenarios with the same name but multiple values. It returns true if the addition is successful and false if it fails (e.g., duplicate value or exceeding the cookie quantity limit).

Note: Cookies are appended using name + domain + path as the unique key.

remove

cookies.remove(name: string, options?: Cookie): boolean;

Removes a Cookie.

Note: Cookies are removed using name + domain + path as the unique key.

Parameters:

Parameter Name Type Required Description
name string Yes The name of the cookie.
options Cookie No Optional Cookie attribute configuration. The domain and path attributes can use the wildcard * to match all.

Limitations

Automatic Escaping of Special Characters

  • The following characters in name values will be automatically escaped: " ( ) , / : ; < = > ? @ [ ] \ { }, 0x00~0x1F, 0x7F~0xFF.
  • The following characters in value values will be automatically escaped: ,, ;, ", \, 0x00~0x1F, 0x7F~0xFF.

Cookie Size Limitations

  • The size of the name attribute of a cookie cannot exceed 64 bytes.
  • The combined size of the value, domain, path, expires, maxAge, and sameSite attributes of a cookie cannot exceed 1KB.
  • The total length of all fields in a cookie after escaping cannot exceed 4KB.
  • The total number of Cookie objects contained in the Cookies object cannot exceed 64.

Code Example

function handleEvent(event) {
  const response = new Response('hello world');

  // Create a Cookies object
  const cookies = new Cookies('ssid=helloworld; expires=Sun, 10-Dec-2023 03:10:01 GMT; path=/; domain=.example.com; samesite=.example.com', true);

  // Set the 'Set-Cookie' response header
  response.headers.set('Set-Cookie', cookies.toString());

  return response;
}

addEventListener('fetch', (event) => {    
  event.respondWith(handleEvent(event));
});

References