4

JS Cookies remove cookie, undefined

Hi Guys, I have trying to remove a cookie from a domain but I can't, the console return undefined.

When I log in the cookie is set up in .dev.books.com but after that the URL change to platform.dev.books.com and keep the same cookies. The name of the cookie I want to remove is bookId, here is my try:

Cookies.set('bookId', ' ');

But instead to change the cookie value, create a new one with the domain platform.dev.books.com

If I use

Cookie.remove('bookId') 

the console return undefined

Thanks, any help will be helpful

rodboc
  • 459
  • 1
  • 8
  • 19

4 Answers4

4
Cookie.remove('bookId') 

^^This wont work. You always need to include the relative path of the current page. Like this:

Cookies.remove('name', { path: '/', domain: '.yourdomain.com' })

The '/' stands for the root page.

2567910
  • 144
  • 5
3

You can unset cookie and set the expire header time to a past date

document.cookie = "bookId=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
Frits
  • 7,341
  • 10
  • 42
  • 60
  • when I do this `document.cookie = "bookId =; expires=Thu, 01 Jan 1970 00:00:00 UTC";` the console return `"bookId=; expires=Thu, 01 Jan 1970 00:00:00 UTC"` but doesn't update the value or remove the cookie :/ – rodboc Jun 30 '16 at 05:21
2

It really depends on the environment, you may have to set the domain attribute that matches the cookie domain stored in the browser

Cookies.remove('name', { domain: 'subdomain.site.com' });

You may encounter mismatch domain if the website is hosted behind a reverse proxy or load-balancer.

Best way to be sure to check the http header with fiddler.

truthseeker
  • 81
  • 1
  • 4
0

Delete a cookie valid to the path of the current page:

Cookies.set('name', 'value', { path: '' })
Cookies.remove('name') // fail!
Cookies.remove('name', { path: '' }) // removed!

IMPORTANT! When deleting a cookie and you're not relying on the default attributes, you must pass the exact same path and domain attributes that were used to set the cookie:

Cookies.remove('name', { path: '', domain: '.yourdomain.com' })

Note: Removing a nonexistent cookie neither raises any exception nor returns any value.

I'll advice you always try to go through the readme of any package you use, thank me latter, lol. https://www.npmjs.com/package/js-cookie

Chukwuemeka Maduekwe
  • 6,687
  • 5
  • 44
  • 67