Updating and Deleting Cookies
You'll learn how to modify existing cookies and properly remove them from the browser.
The Core Idea
Since cookies don't have built-in "update" or "delete" methods, you modify them by overwriting with the same name, and you delete them by setting an expiration date in the past. Think of it like editing a sticky note: you don't erase the old text—you just write a new note with the same label and stick it on top.
Updating a Cookie
To update a cookie, simply use document.cookie again with the same name but new value. All attributes (path, domain, etc.) must match the original cookie for the update to work:
// Original cookie
document.cookie = "username=Alice; path=/; max-age=3600";
// Update the value (keep path and other attributes the same!)
document.cookie = "username=Bob; path=/; max-age=3600";
If the path or domain doesn't match, you'll create a separate cookie instead of updating.
Deleting a Cookie
To delete a cookie, set its expiration to a date in the past. The browser will automatically remove it:
// Delete by setting expires to past date
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
// Or use max-age=0 (often simpler)
document.cookie = "username=; max-age=0; path=/";
Again, the path and domain must exactly match the cookie you're deleting, or you won't actually remove the intended cookie.
The Matching Rule
The browser identifies cookies by name + path + domain. If any of these differ, you're working with a different cookie entirely.
Key Takeaway: Update cookies by resetting them with the same name and matching attributes; delete cookies by setting expires to a past date or max-age=0, ensuring path and domain match the original.