How can I use JavaScript to clear cookies for the current domain?

I’m trying to remove all cookies on the current domain using JavaScript clear cookies logic.

What’s the safest and most reliable way to do this across modern browsers?

JavaScript has no built-in function to delete all cookies at once, but you can loop through them and set their expiry to the past:

document.cookie.split(";").forEach(cookie => {
  const name = cookie.split("=")[0].trim();
  document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;
});

Some cookies may be set with specific paths or domains, so to thoroughly clear them:

function deleteAllCookies() {
  document.cookie.split(";").forEach(cookie => {
    const name = cookie.split("=")[0].trim();

    // Try deleting with common paths
    const paths = ["/", window.location.pathname];
    paths.forEach(path => {
      document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${path};`;
    });
  });
}

If you’re just prototyping and don’t care about precision:

document.cookie = "";

This won’t clear existing cookies but can prevent further issues in a testing context.