How to delete a cookie?
Get rid of a cookie by setting its expiration to a past date:
This process makes the cookie expired, leading to its effective deletion.
Breaking down a Cookie Deletion
Deleting a cookie is not quantum physics, it's about misinforming the browser that the cookie is expired. By setting the expires
attribute to a date in the past, the browser is tricked into discarding the cookie:
This deleteCookie
function can be used to take down a particular cookie by its name. Keep in mind, you'll probably need to match Path
and Domain
attributes if they were set when the cookie was commissioned.
Navigating the Path for Cookie Deletion
Cookies can be stubborn sometimes. They won't just disappear if you don't clear the Path
. If you set a specific path when creating the cookie, make sure to specify the same path during the disposal process:
Issue a deleteCookie('userName', '/app')
command order to effectively target and eliminate a cookie residing in the /app
directory.
Battling with Domains
In some tricky situations, cookies are bound to a specific domain. To delete such elusive cookies, the domain
parameter needs to be correctly set:
For instance, if you're on a mission to remove a cookie associated with a subdomain, you'd execute deleteCookie('userSession', '/', 'sub.example.com')
.
Tackling Browser Quirks
Beware, developers! Internet Explorer doesn't play nice with Max-Age
. For those having to deal with this legacy browser, rely on the trusty expires
attribute. Also, match the cookie's properties like Secure
or HttpOnly
during the deletion process to ensure the security context is the same.
Special Knock-Out for AngularJS
Don't sweat it AngularJS developers, there's a straightforward method for you using the $cookies
service:
Just remember, for your AngularJS app, the ngCookies
module is a prerequisite.
Was this article helpful?