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.
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:
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:
theme=dark; lang=enParsing 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.
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:
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:
dark
nullThe 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:
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:
dark
enThis 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.
Deleting a cookie
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:
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:
nullThe 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.
Why cookie deletion fails
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:
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:
darkThe 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:
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:
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.
Related articles
- How to Manage Cookies in JS: Complete Tutorial -- creating, updating, and configuring cookies with all attributes
- Cookies vs localStorage vs sessionStorage in JavaScript -- comparing the three browser storage mechanisms
- JS localStorage API Guide: A Complete Tutorial -- persistent client-side key-value storage
Quick reference
| Operation | Code |
|---|---|
| Read all cookies | document.cookie |
| Read one cookie | Split on "; " and find the matching name |
| Delete a cookie | Set expires to Thu, 01 Jan 1970 00:00:00 UTC with matching path |
| Handle special chars | Use decodeURIComponent when reading values |
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.
Frequently Asked Questions
Why does deleting a cookie sometimes not work?
Can JavaScript read HttpOnly cookies?
How do I check if a specific cookie exists?
Can I delete cookies from a different domain?
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.
More in this topic
Using Decorators for Logging in JS Architecture
Learn how JavaScript decorators wrap class methods to add logging without touching the original code, including setup with Babel and how execution order works.
JavaScript While Loop Explained: A Complete Guide
A while loop repeats code as long as a condition stays true. Learn the syntax, see practical examples, and understand when a while loop is the right choice over a for loop.
JavaScript Loops Tutorial: for, while, do while
Loops let JavaScript repeat code without writing it twice. Learn the three core loop types, what each one does, and when to choose one over another.