459

Is my function of creating a cookie correct? How do I delete the cookie at the beginning of my program? is there a simple coding?

function createCookie(name,value,days)
function setCookie(c_name,value,1) {
  document.cookie = c_name + "=" +escape(value);
}

setCookie('cookie_name',mac);

function eraseCookie(c_name) {
  createCookie(cookie_name,"",-1);
}
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
kennedy
  • 4,601
  • 2
  • 16
  • 6
  • 3
    w3schools has good functions for cookies at https://www.w3schools.com/js/js_cookies.asp. You can use `setCookie('name', 'value', 0)` to delete a cookie. – Pete Aug 11 '17 at 15:56
  • 1
    This answer worked for me above all the others: https://stackoverflow.com/a/28119715 – JD Smith Oct 07 '20 at 11:58

13 Answers13

415

Try this:

function delete_cookie( name, path, domain ) {
  if( get_cookie( name ) ) {
    document.cookie = name + "=" +
      ((path) ? ";path="+path:"")+
      ((domain)?";domain="+domain:"") +
      ";expires=Thu, 01 Jan 1970 00:00:01 GMT";
  }
}

You can define get_cookie() like this:

function get_cookie(name){
    return document.cookie.split(';').some(c => {
        return c.trim().startsWith(name + '=');
    });
}
Tyler Collier
  • 11,489
  • 9
  • 73
  • 80
ACP
  • 34,682
  • 100
  • 231
  • 371
  • 2
    how do i set a function that and check what is my cookies and whether it expire yet? – kennedy Jan 27 '10 at 03:53
  • @Kennedy jason's answer might be useful – ACP Jan 27 '10 at 03:59
  • i thought of having a function to view my cookie first.. do you have any coding for that? i want to see it when everytime i visit the webpage, it automatically pop-up an alert for it. – kennedy Jan 27 '10 at 04:11
  • 63
    get_cookie is not defined – Kreker Jul 04 '14 at 07:14
  • 12
    The second version of the function no longer works See jsfiddle http://jsfiddle.net/b27Lgxgf/1/. Approach in @Luca 's anwser works – Tasos K. Sep 24 '14 at 13:52
  • 6
    How is this supposed to work? JavaScript doesn't have built-in `get_cookie()` function. – Michał Perłakowski Apr 12 '16 at 19:18
  • 6
    @MichałPerłakowski I'm pretty sure it was only meant to be a placeholder/reference to an actual function you would define elsewhere. – JSeligsohn Feb 21 '18 at 13:38
  • 1
    It is important to remember when testing the cookie has been deleted that you need to refresh the cookies list to see if the cookie has gone, I had to do this in Chrome debugger. – bigdaveygeorge Jun 30 '18 at 12:50
  • I've got a more specific question regarding this, I'll be thankful if you take a look: https://stackoverflow.com/q/53196593/3995261 – YakovL Nov 07 '18 at 20:18
  • Is there an advantage to use `expires=...` instead of `Max-Age=0`? And using the Epoch date with `00:00:01` instead of `00:00:00`? – baptx Jul 19 '21 at 15:41
159

Here a good link on Quirksmode.

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var 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;
}
function eraseCookie(name) {   
    document.cookie = name+'=; Max-Age=-99999999;';  
}
T.Todua
  • 53,146
  • 19
  • 236
  • 237
Luca Matteis
  • 29,161
  • 19
  • 114
  • 169
  • 8
    note: in case not working, make sure `path` is correct. see: https://developers.google.com/web/tools/chrome-devtools/manage-data/cookies – Gayan Weerakutti Mar 07 '17 at 12:22
  • 2
    domain should be added. – Michael Kapustey May 16 '17 at 10:37
  • 5
    Also worth noting that both path ***and*** domain need to have correct values. – Esko Dec 04 '17 at 14:58
  • Tested, works perfectly even in WKWebView, before page loads. Good job on solution. – PashaN Mar 27 '18 at 15:02
  • This one didn't work for me in Firefox (I didn't test it elsewhere). Possible because of the location.host missing. The Luca Borrione answer did; `setCookie(name, "", null , null , null, 1);` Although the other two functions work well. – Chris Pink Aug 09 '18 at 12:15
55

would this work?

function eraseCookie(name) {
    document.cookie = name + '=; Max-Age=0'
}

I know Max-Age causes the cookie to be a session cookie in IE when creating the cookie. Not sure how it works when deleting cookies.

Collin Anderson
  • 14,787
  • 6
  • 68
  • 57
36

Some of the other solutions might not work if you created the cookie manually.

Here's a quick way to delete a cookie:

document.cookie = 'COOKIE_NAME=; Max-Age=0; path=/; domain=' + location.host;

If this doesn't work, try replacing location.host with location.hostname in the snippet above.

Lemmings19
  • 1,383
  • 3
  • 21
  • 34
  • 3
    This was the answer I chose to use, but in my case did not work until I changed it to `location.hostname` – Tom Jul 31 '21 at 19:10
  • 1
    This worked for me also with the exception of implementing what @Tom said. Changing location.host to location.hostname – exceptionsAreBad Sep 17 '21 at 16:34
  • 1
    Doesn't work for me. – aderchox Apr 19 '22 at 08:05
  • 1
    This is the best answer because you don't need complex parsing and selection from all the cookies in document.cookie. The browser will automatically delete the cookie at COOKIE_NAME and leave the rest alone. You can also set a negative value. – Matthew Rideout May 30 '23 at 23:09
19

Here is an implementation of a delete cookie function with unicode support from Mozilla:

function removeItem(sKey, sPath, sDomain) {
    document.cookie = encodeURIComponent(sKey) + 
                  "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + 
                  (sDomain ? "; domain=" + sDomain : "") + 
                  (sPath ? "; path=" + sPath : "");
}

removeItem("cookieName");

If you use AngularJs, try $cookies.remove (underneath it uses a similar approach):

$cookies.remove('cookieName');
Vitalii Fedorenko
  • 110,878
  • 29
  • 149
  • 111
17

You can do this by setting the date of expiry to yesterday.

Setting it to "-1" doesn't work. That marks a cookie as a Sessioncookie.

Undo
  • 25,519
  • 37
  • 106
  • 129
Markus Nordhaus
  • 223
  • 2
  • 2
  • your example does not work if you set cookie on another page and try to delete it from a different page. the set works, but cannot delete it. – chovy Oct 12 '12 at 07:57
  • 2
    I ended up using this: https://github.com/carhartl/jquery-cookie And you have to delete using path: '/' – chovy Oct 12 '12 at 08:20
  • 1
    This is a good approach except... just set expiry time to zero. That will cause instant expiration, and not be confusing to anyone ("Why did the developer set expiry time to yesterday? Was that a mistake, did they want a one-day life span?"). Write code so that it makes more sense, and your life will be less confusing down the line. This is an undervalued philosophy in coding nowadays... Even MDN suggests setting expiry time to zero to delete a cookie. – dudewad Apr 29 '17 at 23:59
16

To delete a cookie I set it again with an empty value and expiring in 1 second. In details, I always use one of the following flavours (I tend to prefer the second one):

1.

    function setCookie(key, value, expireDays, expireHours, expireMinutes, expireSeconds) {
        var expireDate = new Date();
        if (expireDays) {
            expireDate.setDate(expireDate.getDate() + expireDays);
        }
        if (expireHours) {
            expireDate.setHours(expireDate.getHours() + expireHours);
        }
        if (expireMinutes) {
            expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
        }
        if (expireSeconds) {
            expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
        }
        document.cookie = key +"="+ escape(value) +
            ";domain="+ window.location.hostname +
            ";path=/"+
            ";expires="+expireDate.toUTCString();
    }

    function deleteCookie(name) {
        setCookie(name, "", null , null , null, 1);
    }

Usage:

setCookie("reminder", "buyCoffee", null, null, 20);
deleteCookie("reminder");

2

    function setCookie(params) {
        var name            = params.name,
            value           = params.value,
            expireDays      = params.days,
            expireHours     = params.hours,
            expireMinutes   = params.minutes,
            expireSeconds   = params.seconds;

        var expireDate = new Date();
        if (expireDays) {
            expireDate.setDate(expireDate.getDate() + expireDays);
        }
        if (expireHours) {
            expireDate.setHours(expireDate.getHours() + expireHours);
        }
        if (expireMinutes) {
            expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
        }
        if (expireSeconds) {
            expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
        }

        document.cookie = name +"="+ escape(value) +
            ";domain="+ window.location.hostname +
            ";path=/"+
            ";expires="+expireDate.toUTCString();
    }

    function deleteCookie(name) {
        setCookie({name: name, value: "", seconds: 1});
    }

Usage:

setCookie({name: "reminder", value: "buyCoffee", minutes: 20});
deleteCookie("reminder");
Luca Borrione
  • 16,324
  • 8
  • 52
  • 66
14

For people who just want 1 line of code to delete a cookie:

If you created a cookie, for example in a web browser console with document.cookie = "test=hello"

You can delete it with:

document.cookie = "test=;expires=" + new Date(0).toUTCString()

Or if you prefer to write the UTC date directly:

document.cookie = "test=;expires=Thu, 01 Jan 1970 00:00:00 GMT"

If you are on a different path than the cookie (for example if you want to delete a cookie that is used on all paths), you can add path=/; after test=; and if you are on a different domain (for example when a cookie is set for all subdomains by using .example.com instead of www.example.com), you can add domain=.example.com; after test=;.

Update: instead of expires=..., using Max-Age=0 like in other answers works also (tested with Firefox).

baptx
  • 3,428
  • 6
  • 33
  • 42
8

I had trouble deleting a cookie made via JavaScript and after I added the host it worked (scroll the code below to the right to see the location.host). After clearing the cookies on a domain try the following to see the results:

if (document.cookie.length==0)
{
 document.cookie = 'name=example; expires='+new Date((new Date()).valueOf()+1000*60*60*24*15)+'; path=/; domain='+location.host;

 if (document.cookie.length==0) {alert('Cookies disabled');}
 else
 {
  document.cookie = 'name=example; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain='+location.host;

  if (document.cookie.length==0) {alert('Created AND deleted cookie successfully.');}
  else {alert('document.cookies.length = '+document.cookies.length);}
 }
}
John
  • 1
  • 13
  • 98
  • 177
4

I use this on my websites that works on Chrome and Firefox.

function delete_cookie(name) { document.cookie = name +'=; Path=/;  Domain=' + location.host +  '; Expires=Thu, 01 Jan 1970 00:00:01 GMT; SameSite=None; Secure' }
Stan S.
  • 237
  • 7
  • 22
0
if ("JSESSIONID".equals(cookie.getName()) || "LtpaToken2".equals(cookie.getName())) {
                cookie.setValue("");
                cookie.setPath("/");
                cookie.setMaxAge(0);
                cookie.setHttpOnly(true);
                response.addCookie(cookie);
}
Umesh Bhutada
  • 301
  • 2
  • 4
0

I used to generate the cookie from backend and redirect to frontend. The only way I got it working has been to set the expires date in the past in the backned and redirect back on frontend

lcapra
  • 1,420
  • 16
  • 18
0

We don't have the ability to delete cookies in JavaScript, so to delete it we need to create another cookie with an earlier date.

Set Cookie

let expires = null
const cookieName = 'userlogin'
const d = new Date();
d.setTime(d.getTime() + 2 * 24 * 60 * 60 * 1000);
document.cookie = cookieName + "=" + value+ ";" + expires + ";path=/";

Delete Cookie

let expires = null
const d = new Date();
d.setTime(d.getTime() - 2 * 24 * 60 * 60 * 1000);
expires = "expires=" + d.toUTCString();
document.cookie = 'userlogin' + "=" + value+ ";" + expires + ";path=/";