Yes, you can clear cookies with JavaScript by setting their expiration date to a time in the past. The browser then discards the cookie as if it never existed.
Delete a Specific Cookie
To remove one cookie you must write a new cookie with the same name, path and domain, but with an expiration date that has already passed.
- Identify the exact name of the cookie you want to delete.
- Determine the path and domain used when the cookie was created. If you are unsure, use the default values “path=/” and the current host.
- Set the cookie again, adding
expires=Thu, 01 Jan 1970 00:00:00 GMTand the same path and domain.
Example code:
function deleteCookie(name, path = '/', domain) {
let cookieStr = encodeURIComponent(name) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=' + path;
if (domain) cookieStr += '; domain=' + domain;
document.cookie = cookieStr;
}
// Delete a cookie named "sessionId"
deleteCookie('sessionId');
Notice that the function does not attempt to delete HttpOnly cookies. Those are inaccessible to JavaScript.
Remove All Cookies on the Current Site
JavaScript cannot directly list HttpOnly cookies, but it can read the string returned by document.cookie. That string contains every non‑HttpOnly cookie, separated by semicolons.
- Read
document.cookieand split it on;to get individual name‑value pairs. - Trim whitespace and extract the name part of each pair.
- Call the single‑cookie deletion function for each name, using the same path and domain you expect.
Sample implementation:
function deleteAllCookies(path = '/', domain) {
const cookies = document.cookie.split(';');
for (let cookie of cookies) {
const eqPos = cookie.indexOf('=');
const name = eqPos > -1 ? cookie.slice(0, eqPos).trim() : cookie.trim();
deleteCookie(name, path, domain);
}
}
// Remove every accessible cookie on the page
deleteAllCookies();
Running this function clears all cookies that JavaScript can see. It will not affect cookies marked HttpOnly or cookies set on a different sub‑domain.
Cookie Attributes That Affect Deletion
Several attributes control whether a new cookie overwrites an existing one. If any attribute differs, the browser treats the new cookie as a separate entry.
| Attribute | Typical Value When Created | Value Needed to Delete |
|---|---|---|
| name | any string | same string |
| path | / (root) or a sub‑path | identical path |
| domain | current host or a parent domain | identical domain |
Rule of thumb: always specify the same path and domain you used when the cookie was set. If you omit them, the browser assumes path=/ and the current host, which may not match the original cookie.
Limitations: HttpOnly and Secure Cookies
JavaScript cannot read or modify cookies that have the HttpOnly flag. Those cookies are sent only in HTTP requests and are meant to protect session data from client‑side scripts.
If you need to clear an HttpOnly cookie, you must do it from the server side. The server sends a Set-Cookie header with the same name, path, and domain, plus an expired date.
The Secure attribute does not stop JavaScript from deleting the cookie, but it restricts the cookie to HTTPS connections. When you delete a Secure cookie, include the Secure flag in the deletion string to avoid creating a non‑secure version.
Verify Deletion and Common Pitfalls
After you run a deletion script, check that the cookie no longer appears in document.cookie. If it is still present, one of the following issues is likely.
- Mismatched path. The original cookie used
/appwhile the deletion used the default/. Use the exact path. - Mismatched domain. A cookie set for
.example.comwill not be removed by a script that omits the leading dot. Include the domain explicitly. - Missing Secure flag. Deleting a
Securecookie without the flag may create a new, non‑secure cookie with the same name. - HttpOnly cookie. JavaScript cannot see it, so the script appears to succeed while the cookie remains.
To troubleshoot, log the attributes you are using:
console.log('Deleting', name, 'with path', path, 'and domain', domain);
Adjust the values until the cookie disappears from the browser’s storage panel (usually found under DevTools → Application → Cookies).
Practical Workflow for a Typical Site
Most sites set cookies for user preferences, session identifiers, and analytics. The following workflow covers the common case where all cookies are non‑HttpOnly and share the root path.
- Provide a “Clear All Data” button in the UI.
- Attach an event listener that calls
deleteAllCookies()when the button is clicked. - Optionally reload the page to reflect the cleared state.
- If you also use server‑side session cookies, send an Ajax request to an endpoint that clears those cookies via
Set-Cookieheaders.
Example markup and script:
<button id="clearBtn">Clear All Cookies</button>
<script>
document.getElementById('clearBtn').addEventListener('click', function() {
deleteAllCookies();
// Optional: notify server to clear HttpOnly session
fetch('/api/clear-session', {method: 'POST', credentials: 'include'});
location.reload();
});
</script>
This pattern gives the user immediate feedback and ensures both client‑side and server‑side cookies are removed where possible.
When Deletion Fails: Advanced Checks
If after following the steps a cookie still persists, perform these deeper checks.
- Open the browser’s developer tools and view the full cookie list. Note the exact
PathandDomaincolumns. - Check whether the cookie has the
SameSite=StrictorLaxattribute. Those attributes do not affect deletion, but they may indicate the cookie is scoped to a specific sub‑domain. - Inspect the response headers of the page that set the cookie. Look for
Set-Cookielines that includeHttpOnlyor a custom domain.
Armed with that information, craft a precise deletion string that mirrors every attribute. The final string might look like:
document.cookie = 'sessionId=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/app; domain=.example.com; Secure';
When the attributes line up, the browser removes the entry.
Related
- How to Make Calming Chamomile Cookies
- Best Way to Bake Cookies on a Rainy Day
- How to Make Cookies Without a Mixer
General information for everyday wellbeing, not medical advice. If something affects your health, sleep or mood for more than a short while, talk to a qualified professional. Read more
Spotted an error? Tell us and we will correct it (corrections policy).