|
type SameSiteOption = "Lax" | "Strict" | "None"; |
|
|
|
interface CookieOptions { |
|
days?: number; // Number of days until cookie expires. |
|
path?: string; // The path for which the cookie will be available. |
|
domain?: string; // The domain for which the cookie will be available. |
|
secure?: boolean; // If true, the cookie is only sent over secure (HTTPS) connections. |
|
sameSite?: SameSiteOption; // Specifies whether the cookie should be sent with cross-site requests. |
|
} |
|
|
|
/** |
|
* CookieManager - Class for managing cookies. |
|
*/ |
|
|
|
export const CookieManager = { |
|
/** |
|
* Sets a cookie. |
|
* |
|
* @param {string} name - The name of the cookie. |
|
* @param {string} value - The value of the cookie. |
|
* @param {CookieOptions} [options] - Optional parameters for setting the cookie, including expiration, path, domain, secure, and SameSite settings. |
|
* |
|
* @returns {void} |
|
*/ |
|
set: (name: string, value: string, options: CookieOptions = {}): void => { |
|
let { days = 365, path = "/", domain = "", secure = false, sameSite = "Lax" } = options; |
|
let expires = ""; |
|
|
|
if (days) { |
|
const date = new Date(); |
|
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000); // Expiration time in milliseconds |
|
expires = `; expires=${date.toUTCString()}`; |
|
} |
|
|
|
document.cookie = |
|
`${encodeURIComponent(name)}=${encodeURIComponent(value)}${expires}; path=${path}` + |
|
(domain ? `; domain=${domain}` : "") + |
|
(secure ? "; secure" : "") + |
|
`; SameSite=${sameSite}`; |
|
}, |
|
|
|
/** |
|
* Gets a cookie by name. |
|
* |
|
* @param {string} name - The name of the cookie. |
|
* @returns {string | null} - The value of the cookie or null if not found. |
|
*/ |
|
get: (name: string): string | null => { |
|
const cookies = document.cookie |
|
.split("; ") |
|
.reduce((acc: Record<string, string>, cookie: string) => { |
|
const [key, val] = cookie.split("="); |
|
acc[decodeURIComponent(key)] = decodeURIComponent(val); |
|
return acc; |
|
}, {}); |
|
return cookies[name] || null; |
|
}, |
|
|
|
/** |
|
* Deletes a cookie. |
|
* |
|
* @param {string} name - The name of the cookie to delete. |
|
* @param {string} [path] - The path for which the cookie was set. It should match the original path. |
|
* @param {string} [domain] - The domain for which the cookie was set. It should match the original domain. |
|
* |
|
* @returns {void} |
|
*/ |
|
delete: (name: string, path: string = "/", domain: string = ""): void => { |
|
CookieManager.set(name, "", { days: -1, path, domain }); |
|
}, |
|
}; |