All files / src/utils cookies.ts

100% Statements 21/21
100% Branches 7/7
100% Functions 3/3
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46                    4x 87x 87x     87x 87x   87x           4x 106x 106x   106x 116x 116x 116x     78x           4x 15x 15x 15x    
/**
 * Cookie utilities for cross-subdomain token storage
 */
 
import { getCookieDomain } from './domain';
 
/**
 * Set a cookie with domain attribute for cross-subdomain access
 * Dynamically determines the correct domain based on current environment
 */
export const setCookie = (name: string, value: string, days: number = 7) => {
  const expires = new Date();
  expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
 
  // Get cookie domain dynamically (.lvh.me in dev, .smoothschedule.com in prod, localhost for localhost)
  const cookieDomain = getCookieDomain();
  const domainAttr = cookieDomain === 'localhost' ? '' : `;domain=${cookieDomain}`;
 
  document.cookie = `${name}=${value};expires=${expires.toUTCString()}${domainAttr};path=/;SameSite=Lax`;
};
 
/**
 * Get a cookie value by name
 */
export const getCookie = (name: string): string | null => {
  const nameEQ = name + '=';
  const ca = document.cookie.split(';');
 
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) === ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
  }
 
  return null;
};
 
/**
 * Delete a cookie
 */
export const deleteCookie = (name: string) => {
  const cookieDomain = getCookieDomain();
  const domainAttr = cookieDomain === 'localhost' ? '' : `;domain=${cookieDomain}`;
  document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 UTC${domainAttr};path=/;`;
};