Javascript

[Javascript] 🍪 Remove Cookie not working : 쿠키가 삭제되지 않을 때

🚨 문제 상황

react url을 작성해서 접속한 페이지에서 Vanilla Javascript로 작상한 remove cookie가 작동되지 않음

그런데 또 다른데서는 문제없이 됨..🤦‍♂️

//useCookieStorage.ts
export const useCookieStorage = {
  setCookie: (name: string, value: string, exp: number) => {
    let date = new Date();
    date.setTime(date.getTime() + exp * 24 * 60 * 60 * 1000);
    document.cookie = name + '=' + value + ';expires=' + date.toUTCString() + ';path=/';
  },

  getCookie: (name: string) => {
    let nameEQ = name + '=';
    let ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
      let c = ca[i];
      while (c.charAt(0) == ' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
  },

// 여기 ⬇️
  removeCookie: (name: string) => {
    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
  },
};

 

✅ 해결

vanilla JavaScript를 사용하고 있으며 URL에 동적 세그먼트가 있거나

react-router-dom을 통하지 않고 URL에 직접 접근한 경우

removeCookie 함수가 작동하지 않는다면, 이에 대한 몇 가지 이유가 있을 수 있다.

 

1. 쿠키 경로 불일치: 쿠키를 설정할 때는 특정 경로와 연결된다. 다른 경로에서 쿠키를 삭제하려고 한다면 삭제가 작동하지 않을 수 있다. 쿠키를 생성할 때 경로를 적절하게 설정하고, 삭제할 때 해당 경로와 일치시키는 것이 중요하다. path 속성을 사용하여 쿠키를 삭제할 때 경로를 지정하자. (내가 해결한 방법)

function deleteCookie(cookieName, path = '/') {
  document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${path}`;
}

// 특정 경로에 대한 쿠키 삭제
deleteCookie('cookieName', '/specific-path');

 

2. URL 인코딩: 동적 세그먼트나 여러 수준의 URL에 접근할 때, URL을 올바르게 인코딩해야 한다. 쿠키 이름과 경로는 encodeURIComponent를 사용하여 특수 문자나 URL 인코딩된 문자를 처리해야 한다.

const dynamicSegment = '예시 세그먼트';
const encodedSegment = encodeURIComponent(dynamicSegment);

deleteCookie(encodedSegment, '/specific-path');

encodeURIComponent를 사용하여 동적 세그먼트를 인코딩함으로써 쿠키 이름이 올바르게 형식화되도록 한다.

 

👍 적용

;path=/ 경로 추가

 // before - ❌ error
 removeCookie: (name: string) => {
    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
  },

// after - ✅ OK
removeCookie: (name: string) => {
    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/';
  },

 

728x90
반응형