Removing a Cookie

To remove a cookie the Java API suggests getting the cookie, setting its maxAge to 0, and then adding that cookie to the response.  Digging around deeper I realized you also need to set the domain and the path to match the cookie’s domain and path.  Here is an example of how to do this.

    Cookie [] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
      if (cookie.getName().equals(COOKIE_WE_WANT)) {
        cookie.setMaxAge(0);
        cookie.setDomain(".betweengo.com");
        cookie.setPath("/");
        response.addCookie(cookie);
        break;
      }
    }

Note that if the domain was not set when the cookie was created then you should not set it when you try to remove it. Similarly with the path property. For example if the domain was not set at creation then the code would look like this:

    Cookie [] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
      if (cookie.getName().equals(COOKIE_WE_WANT)) {
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        break;
      }
    }

Also you should ensure that you add the cookie to the response before the response has already been committed.  Previously the above code was in a tag but that was too late to modify the response.  I moved this code to a filter and then it worked fine.

Finally you can do this in JavaScript. Doing it in JavaScript has the downside that it is done after the page is loaded. But it’s definitely helpful for testing. Here’s an example of deleting the cookie named “foo”.

document.cookie = 'foo=;expires='+new Date(0).toUTCString()+';';

In the above example I did not set the path or the domain. One will need to do that if the path and/or domain were set in the cookie at creation.

Leave a Reply

Your email address will not be published. Required fields are marked *