Cookies in JavaScript: Get, Set, Delete
How to read, write, and delete cookies with vanilla JavaScript — no library required.
Published:
Tags: JavaScript cookies API, document.cookie JavaScript, set cookie JS
Cookies in JavaScript: Get, Set, Delete is one of JavaScript's most confusing APIs. Despite looking like a simple string property, it behaves differently from any other property: reading returns all cookies, but writing sets one cookie without affecting others. This guide covers the full API with practical patterns, plus the modern alternative. --- All the tools discussed here are available for free at theproductguy.in — client-side, no sign-up required. Part of the HTTP Debugging Tools Guide — a complete toolkit for diagnosing web requests. --- What is The document.cookie API? is a special property with a non-obvious interface: The getter returns all non-HttpOnly cookies. HttpOnly cookies are set by the server and invisible to JavaScript — this is by design, to prevent XSS token theft.…
Frequently Asked Questions
How do I set a cookie in JavaScript?
Assign to document.cookie: document.cookie = 'name=value; path=/; max-age=86400; SameSite=Lax'. Each assignment sets one cookie without clearing others. The browser parses the string to extract the name=value pair and attributes. Despite looking like a simple property assignment, it's a special setter that appends to the cookie jar.
How do I read a cookie in JavaScript?
document.cookie returns all non-HttpOnly cookies as a semicolon-separated string like 'name1=val1; name2=val2'. Parse it manually: document.cookie.split('; ').find(row => row.startsWith('name=')).split('=')[1]. Or use the async cookieStore.get('name') in Chrome 87+.
How do I delete a cookie in JavaScript?
Set the same cookie with max-age=0 or an Expires date in the past: document.cookie = 'name=; path=/; max-age=0'. The name, path, and domain must match the original cookie exactly. If the original cookie had a specific Path or Domain attribute, you must include those when deleting, otherwise you create a new expired cookie rather than removing the original.
What is document.cookie?
document.cookie is a browser property with special getter and setter behavior. Reading it returns a string of all accessible (non-HttpOnly) cookies for the current document. Writing to it sets or updates one cookie — it does not replace all cookies. This non-obvious behavior is a source of confusion for developers new to the API.
How do I use the CookieStore API?
The CookieStore API (cookieStore) is available in Chrome 87+ and provides async get(name), set({name, value, maxAge}), delete(name), and getAll() methods. It returns structured objects instead of requiring string parsing, supports change events via cookieStore.addEventListener('change', handler), and is the modern preferred approach for client-side cookie management.
All articles · theproductguy.in