28 lines
713 B
TypeScript
28 lines
713 B
TypeScript
import { v4 as uuidv4 } from "uuid";
|
|
import { getCookie, removeCookie, setCookie } from "./cookie";
|
|
|
|
const DEVICE_ID_KEY = "x-device-id";
|
|
const COOKIE_DOMAIN = process.env.NEXT_PUBLIC_COOKIE_DOMAIN;
|
|
|
|
export function getOrCreateDeviceId(): string {
|
|
const existing = getCookie(DEVICE_ID_KEY);
|
|
if (existing) return existing;
|
|
|
|
const id = uuidv4();
|
|
const isHttps =
|
|
typeof window !== "undefined" && window.location.protocol === "https:";
|
|
setCookie(DEVICE_ID_KEY, id, {
|
|
secure: isHttps,
|
|
sameSite: "lax",
|
|
domain: COOKIE_DOMAIN,
|
|
path: "/",
|
|
expires: 365,
|
|
});
|
|
|
|
return id;
|
|
}
|
|
|
|
export function clearDeviceId(): void {
|
|
removeCookie(DEVICE_ID_KEY, { domain: COOKIE_DOMAIN, path: "/" });
|
|
}
|