Skip to content

Instantly share code, notes, and snippets.

@russo97
Created March 2, 2024 01:23
Show Gist options
  • Save russo97/cf71edd19b4e7384a2f73f6d7ee9abc6 to your computer and use it in GitHub Desktop.
Save russo97/cf71edd19b4e7384a2f73f6d7ee9abc6 to your computer and use it in GitHub Desktop.
setCookie using a custom JS function
/**
* @typedef {Object} cookieOptions
* @property {Date} expires - optional
* @property {boolean} secure - optional
* @property {'None' | 'Lax' | 'Strict'} sameSite - optional
* @property {string} path - optional
* @property {string} domain - optional
* @property {boolean} httpOnly - optional
*/
/**
*
* @param name {string}
* @param value {string | number | boolean}
* @param options {cookieOptions}
* @returns {string}
*/
function setCookie (name, value, options = {}) {
if (typeof name !== 'string' || name.length === 0) {
throw new Error("'setCookie' should receive a valid cookie name")
}
if (!['string', 'number', 'boolean'].includes(typeof value) || value.toString().length === 0) {
throw new Error("'setCookie' should receive a valid cookie value")
}
/** @type {string[]} */
const cookieOptions = [`${name}=${value}`]
if (options?.expires && options?.expires instanceof Date) {
cookieOptions.push(`expires=` + options.expires.toGMTString())
}
if (options?.sameSite && typeof options?.sameSite === 'string') {
cookieOptions.push(`SameSite=${options?.sameSite}`)
}
if (options?.path && typeof options.path === 'string') {
cookieOptions.push(`path=${options?.path}`)
}
if (options?.domain && typeof options.domain === 'string') {
cookieOptions.push(`domain=${options?.path}`)
}
if (options?.httpOnly && typeof options.httpOnly === 'boolean') {
cookieOptions.push(`HttpOnly`)
}
if (options?.secure && typeof options.secure === 'boolean') {
cookieOptions.push('Secure')
}
const _buildCookie = cookieOptions.join('; ')
document.cookie = _buildCookie
return _buildCookie
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment