How to Delete Cookie in JavaScript: Simple Guide
To delete a cookie in JavaScript, set the cookie with the same name and path but with an expiration date in the past using
document.cookie. This tells the browser to remove the cookie immediately.Syntax
To delete a cookie, you use document.cookie to set the cookie's name and path with an expiration date in the past. This signals the browser to remove it.
cookieName: The name of the cookie you want to delete.path: The path where the cookie was set (must match to delete).expires: Set to a date in the past to delete the cookie.
javascript
document.cookie = "cookieName=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";Example
This example shows how to create a cookie and then delete it by setting its expiration date to a past date.
javascript
document.cookie = "user=John; path=/;"; console.log('Before delete:', document.cookie); document.cookie = "user=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"; console.log('After delete:', document.cookie);
Output
Before delete: user=John
After delete:
Common Pitfalls
Common mistakes when deleting cookies include:
- Not matching the
pathordomainof the original cookie, so the browser does not delete it. - Forgetting to set the
expiresattribute to a past date. - Trying to delete cookies set with
HttpOnlyflag, which JavaScript cannot access.
javascript
/* Wrong: Missing path, cookie may not delete */ document.cookie = "user=; expires=Thu, 01 Jan 1970 00:00:00 GMT"; /* Right: Matching path to delete cookie */ document.cookie = "user=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
Quick Reference
| Action | Code Example |
|---|---|
| Delete cookie named 'session' | document.cookie = "session=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"; |
| Delete cookie with specific path | document.cookie = "token=; path=/app; expires=Thu, 01 Jan 1970 00:00:00 GMT"; |
| Delete cookie with domain | document.cookie = "id=; domain=example.com; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"; |
Key Takeaways
Delete cookies by setting their expiration date to a past date using document.cookie.
Always match the original cookie's path and domain to successfully delete it.
JavaScript cannot delete HttpOnly cookies set by the server.
Use the exact cookie name when deleting to avoid leaving cookies behind.
Check document.cookie before and after deletion to confirm removal.