✅ To delete a cookie:
- Create a new cookie with the same name as the one you want to delete.
- Set its
Max-Age
to 0. - (Optional but important) Set the same
path
as the original cookie (otherwise it might not match).
Finally, add it to the response.
🎯 Example: Deleting a Cookie
Cookie cookie = new Cookie("userName", ""); // Name must match
cookie.setMaxAge(0); // 0 means delete immediately
cookie.setPath("/"); // Must match original path
response.addCookie(cookie); // Add it back to instruct browser
✅ What happens:
- When the browser receives a cookie with
Max-Age=0
, it removes the cookie immediately.
⚡ Important Things to Remember:
Point | Why |
---|---|
Cookie name must match exactly | Otherwise the browser doesn’t know which cookie to remove |
Cookie path must match | If path differs, it won’t recognize the cookie to delete |
Domain (if set originally) must match | Otherwise browser might keep old cookie |
Always addCookie() even for deletion | Deleting is just sending a “zero-age” cookie back |
🚀 Practical Full Example
✅ Suppose you earlier created:
Cookie cookie = new Cookie("userName", "Alice");
cookie.setMaxAge(3600);
cookie.setPath("/");
response.addCookie(cookie);
✅ Now to delete it later:
Cookie deleteCookie = new Cookie("userName", "");
deleteCookie.setMaxAge(0);
deleteCookie.setPath("/");
response.addCookie(deleteCookie);
🔥 Real Life Scenario
- After a user logs out, you usually delete session-related cookies like “userId” or “JSESSIONID” (if not managed automatically).
- Important for security and privacy.
🛠️ Quick Summary:
Can I delete a cookie? | ✅ Yes |
How? | Set Max-Age = 0 and addCookie() |
Should name and path match original? | ✅ Yes, absolutely |
Browser behavior | Browser removes the cookie immediately |
⚡ Final Memory Trick:
“To delete a cookie: same name + same path + Max-Age 0 + send it back.” 🎯