Explain Codes LogoExplain Codes Logo

How to delete a cookie?

javascript
cookie-engineering
browser-quirks
javascript-apis
Alex KataevbyAlex Kataev·Sep 3, 2024
TLDR

Get rid of a cookie by setting its expiration to a past date:

document.cookie = "cookieName=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";

This process makes the cookie expired, leading to its effective 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:

function deleteCookie(name) { // Set the cookie with a Past Expiry date, time travel anyone? document.cookie = name + '=; Max-Age=-99999999;'; }

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.

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:

function deleteCookie(name, path = '/') { document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=' + path; }

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:

function deleteCookie(name, path = '/', domain) { let cookieStr = name + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=" + path; if (domain) { cookieStr += "; domain=" + domain; } document.cookie = cookieStr; }

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:

$cookies.remove('cookieName');

Just remember, for your AngularJS app, the ngCookies module is a prerequisite.