Parsing and Deleting Browser Cookies with JS

Learn how to read, parse, and delete browser cookies using JavaScript. Includes practical parsing functions, deletion patterns, and common pitfalls.

5 min read

Browsers store cookies as a single, unwieldy string accessible through document.cookie. There is no built-in getCookie or deleteCookie method. To work with cookies in JavaScript, you need to parse that string yourself and understand how browsers decide whether to accept a deletion.

Here is the basic flow. Setting and reading cookies uses the same property in two very different ways:

javascriptjavascript
document.cookie = "theme=dark";
document.cookie = "lang=en";
console.log(document.cookie);

Assigning to document.cookie adds or updates one cookie at a time without touching others. Reading it back returns every visible cookie for this domain as a single semicolon-separated string:

texttext
theme=dark; lang=en

Parsing that semicolon-separated string into individual cookies is where the work begins.

How document.cookie works

document.cookie behaves unlike any other JavaScript property. When you read it, you get all visible cookies as one string. When you write to it, you set a single cookie without overwriting the others.

Cookie read and write through document.cookie

The read path collects every non-HttpOnly cookie the browser holds for the current domain. The write path applies the cookie's attributes based on what you include in the assignment string, then stores or updates the matching cookie.

Parsing cookies into usable values

The raw document.cookie string looks like "theme=dark; lang=en; sessionId=abc123". To find a specific cookie, split, trim, and map the pairs:

javascriptjavascript
function getCookie(name) {
  const cookies = document.cookie.split("; ");
  for (const cookie of cookies) {
    const [key, ...rest] = cookie.split("=");
    if (key === name) {
      return decodeURIComponent(rest.join("="));
    }
  }
  return null;
}
 
console.log(getCookie("theme"));
console.log(getCookie("missing"));

The getCookie function finds the matching cookie by name and returns its value. When the cookie does not exist, it returns null instead of throwing an error:

texttext
dark
null

The function splits on semicolon followed by space, which matches the browser's separator format. Using decodeURIComponent handles special characters. The spread operator on rest handles cookie values that themselves contain equals signs.

Parsing all cookies into an object

When you need to read multiple cookies at once, parsing the entire string into an object is more efficient:

javascriptjavascript
function parseCookies() {
  const result = {};
  document.cookie.split("; ").forEach((cookie) => {
    const [name, ...rest] = cookie.split("=");
    if (name) {
      result[name.trim()] = decodeURIComponent(rest.join("="));
    }
  });
  return result;
}
 
const cookies = parseCookies();
console.log(cookies.theme);
console.log(cookies.lang);

Parsing all cookies at once creates a plain object where each key maps to a cookie name. Here are the values for the theme and lang cookies:

texttext
dark
en

This creates a plain object where each key is a cookie name. Use this pattern when checking multiple cookies on page load, like reading all user preferences at once.

A cookie is deleted by setting its expiration date to a time in the past. The browser sees the expired date and removes the cookie:

javascriptjavascript
document.cookie = "theme=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
console.log(getCookie("theme"));

Setting the expiration to the Unix epoch removes the cookie from the browser. The subsequent getCookie call confirms it is gone:

texttext
null

The value can be empty, but the expires date must be in the past. The path parameter is critical. If the cookie was originally set with a specific path, you must use the same path to delete it.

The most common reason a cookie refuses to die is a path mismatch. Here a cookie is created with path=/settings but deleted with the default path:

javascriptjavascript
document.cookie = "sitePref=dark; path=/settings";
document.cookie = "sitePref=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
 
console.log(getCookie("sitePref"));

Deleting with the wrong path has no effect. The browser treats path=/settings and path=/ as different cookie scopes, so the original cookie lives on:

texttext
dark

The cookie survives because the browser treats cookies with different paths as separate. The fix is to match the original path exactly when deleting. A general-purpose delete function should accept a path parameter:

javascriptjavascript
function deleteCookie(name, path = "/") {
  document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${path}`;
}
 
deleteCookie("sitePref", "/settings");

If you do not control the original cookie's path, you may need to try deleting it with the most common paths: /, the current page path, and any subdirectory paths your app uses.

Deleting domain-scoped cookies

Cookies set with an explicit domain attribute need that domain in the deletion:

javascriptjavascript
function deleteCookieWithDomain(name, path = "/", domain = "") {
  let cookieString = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${path}`;
  if (domain) {
    cookieString += `; domain=${domain}`;
  }
  document.cookie = cookieString;
}
 
deleteCookieWithDomain("session", "/", ".example.com");

Without the matching domain, the browser ignores the deletion. If unsure of the original domain, try deleting both with and without it, and also with a leading dot.

What you cannot do with document.cookie

document.cookie has hard limitations by design. HttpOnly cookies set by the server are invisible to JavaScript, and you can see names and values but not the expiration date, path, domain, Secure, or SameSite flags of a cookie.

Cross-domain cookie access is blocked by the browser entirely.

Common mistakes

  • Using the wrong path when deleting. Match the original cookie's path exactly.
  • Forgetting decodeURIComponent when reading values. Cookie values may contain percent-encoded characters.
  • Splitting on the wrong separator. Always split on "; " with a space, not just ";".
  • Assuming all cookies are visible. HttpOnly cookies are missing from document.cookie by design.
  • Setting a cookie too large. Browsers limit individual cookie size to about 4 KB.

Quick reference

OperationCode
Read all cookiesdocument.cookie
Read one cookieSplit on "; " and find the matching name
Delete a cookieSet expires to Thu, 01 Jan 1970 00:00:00 UTC with matching path
Handle special charsUse decodeURIComponent when reading values
Rune AI

Rune AI

Key Insights

  • document.cookie returns all non-HttpOnly cookies as a single semicolon-separated string.
  • Parse cookies by splitting on semicolons and mapping names to values with decodeURIComponent.
  • Delete a cookie by setting its expiration date to the past with the same path and domain.
  • HttpOnly cookies are invisible to JavaScript and cannot be read or deleted from the client.
RunePowered by Rune AI

Frequently Asked Questions

Why does deleting a cookie sometimes not work?

A cookie's deletion must match its original path and domain. If a cookie was set with path=/admin, deleting it with the default path will fail. Always include the same path and domain when deleting.

Can JavaScript read HttpOnly cookies?

No. Cookies marked HttpOnly are invisible to JavaScript. They are only sent in HTTP requests and are used for sensitive tokens like session IDs. document.cookie will never include them.

How do I check if a specific cookie exists?

Parse document.cookie and look for the cookie name. If the parsed value is not null, the cookie exists. Use the cookie parsing function shown in this article.

Can I delete cookies from a different domain?

No. JavaScript can only read and delete cookies belonging to the current page's domain. You cannot touch cookies set by other sites.

Conclusion

Reading cookies from document.cookie requires parsing, but once you have a small utility function, it is straightforward. Deleting cookies is trickier: you must match the path and domain exactly, or the cookie survives the deletion attempt. For managing cookies including creation and expiration, see the companion article on cookie management.