const PUBLIC_SUFFIX_BLOCKLIST = new Set([ "localhost", "127.0.0.1", ]); export function getCookieDomain(hostname: string): string | undefined { if (!hostname) return undefined; const cleanHost = hostname.toLowerCase().split(":")[0]; // 1. Local / dev environments → no domain if (PUBLIC_SUFFIX_BLOCKLIST.has(cleanHost) || cleanHost.endsWith(".local")) { return undefined; } const parts = cleanHost.split(".").filter(Boolean); // 2. IP address → no domain cookies const isIp = parts.every((p) => /^\d+$/.test(p)); if (isIp) return undefined; // 3. Must have at least domain + tld if (parts.length < 2) return undefined; // 4. Handle common case: api.example.com → example.com const rootDomain = parts.slice(-2).join("."); // 5. Safety: avoid setting cookie on known public suffix-like domains const unsafeTlds = new Set([ "vercel.app", "netlify.app", "github.io", "firebaseapp.com", ]); if (unsafeTlds.has(rootDomain)) { return undefined; } return `.${rootDomain}`; }