/ shared / components / src / utils / cookie.ts
cookie.ts
 1  export function getCookie(name: string): string | null {
 2      if (typeof document === 'undefined') {
 3          return null;
 4      }
 5  
 6      const prefix = `${name}=`;
 7      const cookie = document.cookie
 8          .split(';')
 9          .map((value) => value.trimStart())
10          .filter((value) => value.startsWith(prefix))[0];
11  
12      if (!cookie) {
13          return null;
14      }
15  
16      return cookie.substr(prefix.length);
17  }
18  
19  export function setCookie(
20      name: string,
21      value: string,
22      domain: string,
23      expires = 0,
24      path = '/',
25  ): void {
26      if (typeof document === 'undefined') {
27          return undefined;
28      }
29  
30      // Get any potential existing instances of this particular cookie
31      const existingCookie = getCookie(name);
32      let cookieValue = value;
33  
34      if (existingCookie) {
35          // If exisitng cookie name does not include the value we are trying to set,
36          // then add it, otherwise use the existing cookie value
37          cookieValue = !existingCookie.includes(value)
38              ? `${existingCookie}+${value}`
39              : existingCookie;
40      }
41  
42      let cookieString = `${name}=${cookieValue}; path=${path}; domain=${domain};`;
43  
44      if (expires) {
45          const date = new Date();
46          date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1000);
47  
48          cookieString += ` expires=${date.toUTCString()};`;
49      }
50  
51      document.cookie = cookieString;
52  
53      // Returning undefined because of ESLint's "consistent-return" rule
54      return undefined;
55  }
56  
57  export function clearCookie(name: string, domain: string, path = '/'): void {
58      if (typeof document === 'undefined') {
59          return undefined;
60      }
61  
62      // Get any potential existing instances of this particular cookie
63      const existingCookie = getCookie(name);
64  
65      if (existingCookie) {
66          // Set the cookie's expiration date to a past date
67          setCookie(name, '', domain, -1, path);
68      }
69  
70      return undefined;
71  }