1

I'm having trouble with cookies and getting some weird behavior. For now the cookie are set on sign in like so:

document.cookie = "cookie1=" + cookie1 + "; expires=0; path=/";
document.cookie = "basicAuth=" + basicAuth + "; expires=0; path=/";
document.cookie = "cookie2=" + cookie2 + "; expires=0; path=/"

That works fine. I have a sign out button in the header and on click it does the following:

document.cookie = "cookie1=";
document.cookie = "basicAuth=";
document.cookie = "cookie2=";

In the header script I have a simple check to see if cookie1 is empty and to hide the header nav bar and redirect to sign in if it is:

if (getCookie("cookie1") == "") {
    $(".navbar").css({"display":"none"});
    window.location.href = "/signin";
}

Right now I am able to log out effectively the first time, but logging back in and logging out again seems not to work properly. I still see the navbar and the redirect seems to only work selectively. Is there a better way to set or delete cookies?

Jeastburn
  • 95
  • 1
  • 11

1 Answers1

1

When you delete a cookie, you should also add the date and path, and the date should be in the past to remove the cookie, so something like

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

The specification says

...to remove a cookie, the server returns a Set-Cookie header with an expiration date in the past. The server will be successful in removing the cookie only if the Path and the Domain attribute in the Set-Cookie header match the values used when the cookie was created.

Cookies are generally easier to work with in Javascript if you use helper functions that set the name, value, UTC timestamp etc. for you, instead of doing it every time you set or get a cookie.

What you're doing just sets the cookie to an empty string, it's never really removed.

Community
  • 1
  • 1
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • This works well thank you. I'm running into an issue where it works whenever it's calls from a sub-domain (www.foo.com/bar), but not from a sub-sub-domain (www.foo.com/bar/foobar). Any idea why this would be the case? – Jeastburn Dec 29 '15 at 22:50
  • I've found the problem I was having and fixed my issue. When called from a sub-subpath (/bar/foobar) it wasn't working because I wasn't specifying a cookie path. So the cookie expiration only worked on that subpath (/bar/), not more generally on the site. This was fixed by seting it to `document.cookie = "cookie1=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/";` Adeneo, I'm going to leave yours as the answer because it was what the question was asking but want to clarify for others to find if they have the same issue. – Jeastburn Dec 30 '15 at 19:13
  • Well, my answer is the answer, you should always have a date and a path when setting cookies – adeneo Dec 30 '15 at 19:56