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);
}
2

14 Answers 14

416

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 + '=');
    });
}
10
  • 2
    how do i set a function that and check what is my cookies and whether it expire yet?
    – kennedy
    Jan 27, 2010 at 3:53
  • 63
    get_cookie is not defined
    – Kreker
    Jul 4, 2014 at 7:14
  • 12
    The second version of the function no longer works See jsfiddle jsfiddle.net/b27Lgxgf/1. Approach in @Luca 's anwser works
    – Tasos K.
    Sep 24, 2014 at 13:52
  • 6
    How is this supposed to work? JavaScript doesn't have built-in get_cookie() function. Apr 12, 2016 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, 2018 at 13:38
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;';  
}
5
  • 8
    note: in case not working, make sure path is correct. see: developers.google.com/web/tools/chrome-devtools/manage-data/… Mar 7, 2017 at 12:22
  • 2
    domain should be added. May 16, 2017 at 10:37
  • 5
    Also worth noting that both path and domain need to have correct values.
    – Esko
    Dec 4, 2017 at 14:58
  • Tested, works perfectly even in WKWebView, before page loads. Good job on solution.
    – PashaN
    Mar 27, 2018 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 9, 2018 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.

2
  • 4
    Set to zero, the cookie will expire when the browser window closes. Jun 19, 2020 at 19:59
  • 1
    @AyexeM refreshing the windows does the job also
    – Kevin O.
    Feb 13, 2022 at 20:11
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.

4
  • 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, 2021 at 19:10
  • 1
    This worked for me also with the exception of implementing what @Tom said. Changing location.host to location.hostname Sep 17, 2021 at 16:34
  • 1
    Doesn't work for me.
    – aderchox
    Apr 19, 2022 at 8: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. May 30 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');
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.

3
  • 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, 2012 at 7:57
  • 2
    I ended up using this: github.com/carhartl/jquery-cookie And you have to delete using path: '/'
    – chovy
    Oct 12, 2012 at 8: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, 2017 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");
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).

1
  • That only works with dev console, unfortunately. Logout.php script doesn't Jan 22 at 13:37
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);}
 }
}
0
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' }
0
if ("JSESSIONID".equals(cookie.getName()) || "LtpaToken2".equals(cookie.getName())) {
                cookie.setValue("");
                cookie.setPath("/");
                cookie.setMaxAge(0);
                cookie.setHttpOnly(true);
                response.addCookie(cookie);
}
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

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=/";
0

If you want to erase every single cookie at once, define the eraseCookies function like this:

function eraseCookies() {
    cookies = document.cookie.split("; ").map((a) => a.split("=")[0]) // Get the cookie names
    for (var i in cookies) {
        document.cookie = cookies[i] + "=;expires=" + new Date(0).toUTCString() // Erase each cookie
    }
}

Then you can erase all cookies by calling eraseCookies with no arguments.

Credits to this answer for how to erase a single cookie.

Not the answer you're looking for? Browse other questions tagged or ask your own question.