/** * Cookie Helpers for UTM Parameter Storage * * Provides Base64-encoded JSON cookie storage for UTM parameters. */ import type { UTMProperties } from "../types/utm"; import { Base64 } from "js-base64"; import Cookies from "js-cookie"; const UTM_COOKIE_KEY = "utm_parameters"; const DEFAULT_DOMAIN = ".gokinetic.com"; /** * Reads UTM parameters from the Base64-encoded cookie. * @returns Parsed UTMProperties or null if cookie doesn't exist / is invalid. */ export function getUTMs(): UTMProperties | null { if (typeof window === "undefined") return null; const raw = Cookies.get(UTM_COOKIE_KEY); if (!raw) return null; try { const decoded = Base64.decode(raw); return JSON.parse(decoded) as UTMProperties; } catch { return null; } } /** * Stores UTM parameters as a Base64-encoded JSON cookie. * @param utms - The UTM properties to store. * @param domain - Cookie domain (defaults to `.gokinetic.com`). */ export function setUTMs( utms: UTMProperties, domain: string = DEFAULT_DOMAIN ): void { if (typeof window === "undefined") return; const json = JSON.stringify(utms); const encoded = Base64.encode(json); Cookies.set(UTM_COOKIE_KEY, encoded, { domain, path: "/", sameSite: "Lax", }); } /** * Removes the UTM cookie. * @param domain - Cookie domain (defaults to `.gokinetic.com`). */ export function removeUTMs(domain: string = DEFAULT_DOMAIN): void { Cookies.remove(UTM_COOKIE_KEY, { domain, path: "/" }); } export function getCookie(key: string): string | null { if (typeof window === "undefined") return ""; const encryptedValue = Cookies.get(key); if (encryptedValue) return Base64.decode(encryptedValue); return null; } export const getParsedCookie = (key: string) => { try { return JSON.parse(getCookie(key) || ""); } catch { return null; } }; export const setCookie = ( key: string, value: any, options: Cookies.CookieAttributes ) => { if (typeof window === "undefined") return; const stringValue = JSON.stringify(value); const encryptedValue = Base64.encode(stringValue); Cookies.set(key, encryptedValue, options); };