While I’ve blogged about cookie grief before, I spent most of yesterday discovering more than a man should about cookie deletion. So I’m iterating over request.getCookies()
and finding the relevant cookie to delete, then calling setMaxAge(0)
to expire it immediately. What could go wrong?
Well… the cookie wasn’t disappearing. These things can be a bit of a bugger to track down since you need to see the browser and response headers to work out what is going on. The tool I like best for this is ieHttpHeaders (an IE equivalent of livehttpheaders).
My first drama was that I wasn’t seeing the Set-Cookie
header come back to the browser to delete the cookie. Hmm… seems you’ve got to add the cookie to the response once you do the setMaxAge(0)
on it. Probably should have known that. No biggy… Try again…
Ok. Now I see the Set-Cookie
coming back to the browser header to kill off the cookie, but on then next request, the browser is still sending the cookie to the server! After much stuffing around I noticed that when I created the cookie, the Set-Cookie
header has a path and domain, but when I delete the cookie there’s no such beast. You’d think I could call Cookie.getDomain()
and Cookie.getPath()
on the cookie I retrieve from the request. No cigar. The browser doesn’t tell you that stuff, so you just get nulls.
So then I changed my deleteCookie routine to call the same code that generated the Cookie in the first place (with domain, path, and age), and call setMaxAge(0)
on that and add it to the response. All good.
The moral of the story is that setMaxAge(0)
only does what you think it does if the path and domain match the ones you used to set the cookie in the first place. Of course, once you know about it, you find out that it’s a well known thing anyways…
Blogging it up so that Google may save you from setMaxAge(0)
pain in the future…