Skip to content

Instantly share code, notes, and snippets.

@westc
Created August 15, 2023 23:05
Show Gist options
  • Save westc/6d2bdb9df9fde522b3137ceca062b664 to your computer and use it in GitHub Desktop.
Save westc/6d2bdb9df9fde522b3137ceca062b664 to your computer and use it in GitHub Desktop.
Functions to get, set and delete cookies.
/**
* Gets all of the cookies as an object.
* @returns {{[key: string]: string}}
* An object where the keys are the names of the cookies and the values are
* the corresponding values as strings.
*/
function getAllCookies() {
return Array.from(document.cookie.matchAll(/([^;\s=]*)=([^;\s=]*)/g)).reduce(
(byName, [_, key, value]) => {
byName[decodeURIComponent(key)] = decodeURIComponent(value);
return byName;
},
{}
);
}
/**
* Sets the specified cookie.
* @param {string} name
* The name of the cookie to set.
* @param {string} value
* The value of the cookie to set.
* @param {?setCookieOptions=} options
* Optional. The options that you want to set.
* @returns {string=}
* Returns the previous value for the cookie of the specified `name`.
*/
function setCookie(name, value, options) {
let {domain, expires, maxAge, partitioned, path, samesite, secure} = options ?? {};
let lastValue = getAllCookies()[name];
document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`
+ (domain ? `;domain=${domain}` : '')
+ (expires ? `;expires=${expires.toUTCString()}` : '')
+ (maxAge ? `;max-age=${maxAge}` : '')
+ (partitioned ? ';partitioned' : '')
+ (path ? `;path=${path}` : '')
+ (samesite ? ';samesite' : '')
+ (secure ? ';secure' : '');
return lastValue;
}
/**
* Deletes the specified cookie.
* @param {string} name
* The name of the cookie to delete.
* @param {Omit<setCookieOptions, "expires"|"maxAge">} options
* Optional. The options used when setting the cookie (excluding `expires`
* and `maxAge`).
* @returns {string=}
* Returns the value for the cookie before it was deleted.
*/
function deleteCookie(name, options) {
options ??= {};
delete options.expires;
options.maxAge = -1;
return setCookie(name, '', options);
}
/**
* @typedef setCookieOptions
* @property {string=} domain
* The host to which the cookie will be sent. If not specified, this defaults
* to the host portion of the current document location.
* @property {Date=} expires
* When the cookie will expire.
* @property {number=} maxAge
* The max age in seconds.
* @property {boolean=} partitioned
* Indicates that the cookie should be stored using partitioned storage.
* @property {boolean=} path
* Indicates the path that must exist in the requested URL for the browser to
* send the Cookie header (e.g., `'/'`, `'/mydir'`). If not specified, it
* defaults to the current path of the current document location.
* @property {("lax"|"strict"|"none")=} samesite
* SameSite prevents the browser from sending this cookie along with
* cross-site requests.
* @property {boolean=} secure
* Specifies that the cookie should only be transmitted over a secure
* protocol.
*/
setCookie('name', 'John', {
path: '/',
maxAge: 3600
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment