ConfusedDeer ConfusedDeer - 6 months ago 16
Javascript Question

Why am I not able to delete a cookie using Cookie.js?

I'm using Jscookie.js
I'm passing down a cookie (on the header) on the response from my server.
I can see using cookiemanager+ that the client receives the cookie. My JavaScript attempts to delete the cookie, but the cookie is not being deleted.

Oddly enough, when I run the project locally the cookie is deleted successfully, but when I deploy to my test server the cookie does not get deleted.

My server code:

var DownloadToken = request.Headers.GetCookies(UploadToken").FirstOrDefault();
if (DownloadToken != null)
{
var cookie = new CookieHeaderValue("DownloadToken", DownloadToken["UploadToken"].Value.ToString()); //create a new cookie
cookie.Expires = System.DateTime.Now.AddMinutes(6.0); //expire cookie in 6 minutes
cookie.Domain = request.RequestUri.Host == "localhost" ? null : request.RequestUri.Host;
cookie.Path = "/";
response.Headers.AddCookies(new CookieHeaderValue[] {cookie});
}

return response;


MY client code:

Cookies.remove('DownloadToken'); //clears this cookie value for fileDownloadToken

Answer

On the server my cookie.domain was being set, so when I tried to remove the cookie on the client after it was passed down it would not work, because in order to remove the cookie I had to specify the domain.

For example, I updated my server code that creates the cookie, so it adds the domain. Also updated client code that removes the cookie to specify the domain when removing the cooke:

On server:

var DownloadToken = request.Headers.GetCookies(UploadToken").FirstOrDefault();
                if (DownloadToken != null)
                {
                    var cookie = new CookieHeaderValue("DownloadToken", DownloadToken["UploadToken"].Value.ToString());  //create a new cookie
                    cookie.Expires = System.DateTime.Now.AddMinutes(6.0); //expire cookie in 6 minutes
                    cookie.Domain = request.RequestUri.Host == "localhost" ? null : ".mywebsite.com";
                    cookie.Path = "/";
                    response.Headers.AddCookies(new CookieHeaderValue[] {cookie});
                }

return response;

and on client:

Cookies.remove('DownloadToken', { domain: '.mywebsite.com' });