getCartToken.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { GUEST_CART_TOKEN, IS_GUEST } from "@/utils/constants";
  2. import { decodeJWT } from "@/utils/jwt-cookie";
  3. export const getNativeCookie = (name: string): string | null => {
  4. if (typeof document === "undefined") return null;
  5. const cookies = document.cookie.split("; ").map((c) => c.trim());
  6. const found = cookies.find((c) => c.startsWith(name + "="));
  7. return found ? decodeURIComponent(found.split("=")[1]) : null;
  8. };
  9. export const getCartToken = (): string | null => {
  10. const raw = getNativeCookie(GUEST_CART_TOKEN);
  11. if (!raw) return null;
  12. const isGuest = getNativeCookie(IS_GUEST) !== "false";
  13. const decoded = decodeJWT<{ sessionToken: string }>(raw, isGuest);
  14. return decoded?.sessionToken ?? null;
  15. };
  16. // fetch any cookie data
  17. export const getCookie = (name: string): string | null => {
  18. if (typeof document === "undefined") return null;
  19. const match = document.cookie.match(new RegExp("(^| )" + name + "=([^;]+)"));
  20. return match ? decodeURIComponent(match[2]) : null;
  21. };
  22. export const setCookie = (name: string, value: string, days = 7) => {
  23. if (typeof document === "undefined") return;
  24. const expires = new Date(Date.now() + days * 864e5).toUTCString();
  25. document.cookie = `${name}=${value}; expires=${expires}; path=/`;
  26. };
  27. export const deleteCookie = (name: string) => {
  28. if (typeof document === "undefined") return;
  29. document.cookie = `${name}=; Max-Age=0; path=/`;
  30. };