You can delete a Cookie by setting its expiration date to the past. Browser will automatically remove such Cookies. 🗑️
// Delete specific cookie
document.cookie = 'username=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
// Important: path and domain must match original cookie!Deleting a Cookie is like throwing away an expired note. You need to put an “expired” date on it and browser will throw it away automatically! 📝❌
Main method — set expiration date to the past:
// Delete cookie by setting past date
document.cookie = 'username=; expires=Thu, 01 Jan 1970 00:00:00 GMT';// If cookie was set with path
document.cookie = 'theme=dark; path=/admin';
// Then deletion must specify same path
document.cookie = 'theme=; path=/admin; expires=Thu, 01 Jan 1970 00:00:00 GMT';// If cookie was set with domain
document.cookie = 'user=john; domain=.example.com';
// Then deletion must specify same domain
document.cookie = 'user=; domain=.example.com; expires=Thu, 01 Jan 1970 00:00:00 GMT';function deleteCookie(name) {
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
}
// Use it
deleteCookie('username');function deleteCookie(name, path = '/', domain = '') {
let cookieString = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=${path}`;
if (domain) {
cookieString += `; domain=${domain}`;
}
document.cookie = cookieString;
}
// Delete with specific path
deleteCookie('theme', '/admin');// ✅ Delete auth data
document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
document.cookie = 'userId=; expires=Thu, 01 Jan 1970 00:00:00 GMT';// ✅ Delete user settings
document.cookie = 'language=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
document.cookie = 'theme=; expires=Thu, 01 Jan 1970 00:00:00 GMT';// ✅ Delete old cookies
document.cookie = 'oldSetting=; expires=Thu, 01 Jan 1970 00:00:00 GMT';// ❌ Error — cookie won't delete if parameters don't match
document.cookie = 'user=john; path=/admin; domain=.example.com';
document.cookie = 'user=; expires=Thu, 01 Jan 1970 00:00:00 GMT'; // No path and domain!
// ✅ Correct — all parameters match
document.cookie = 'user=; path=/admin; domain=.example.com; expires=Thu, 01 Jan 1970 00:00:00 GMT';// ❌ Impossible — HttpOnly cookies can't be deleted via JavaScript
// Only server can set such cookies
// document.cookie = 'serverToken=; expires=...'; // Won't work!expires=Thu, 01 Jan 1970 00:00:00 GMT ⏰Understanding how to delete Cookies helps manage user data correctly! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪