Reading and Writing Cookies
The document.cookie quirk
Section titled “The document.cookie quirk”document.cookie does not behave like a normal JavaScript property. It has two completely different behaviors depending on whether you read it or write to it.
Reading returns ALL cookies for the current page as a single semicolon-separated string:
// If three cookies are set:console.log(document.cookie);// "theme=dark; user=Alice; lang=en"Writing sets (or updates) ONE cookie — it does not replace all cookies:
document.cookie = 'theme=light; Max-Age=86400; SameSite=Lax';// Only theme is updated — other cookies are untouchedThis asymmetry is the most surprising part of the cookies API. Writing to document.cookie is more like calling a setCookie() function than assigning to a string property.
Setting a cookie
Section titled “Setting a cookie”The syntax for setting a cookie is a string with the name=value first, followed by optional attributes separated by semicolons:
// Session cookie (no Expires/Max-Age — deleted when browser closes)document.cookie = 'demo_pref=dark; SameSite=Lax';
// Persistent cookie (survives browser restarts)document.cookie = 'demo_pref=dark; Max-Age=86400; SameSite=Lax';
// Path-scoped cookiedocument.cookie = 'demo_pref=dark; Max-Age=86400; Path=/app; SameSite=Lax';Always include SameSite=Lax as a minimum for client-set cookies. Modern browsers default to Lax for cookies set without a SameSite attribute, but being explicit is safer.
Reading a specific cookie
Section titled “Reading a specific cookie”Because reading document.cookie returns all cookies as one string, you need to parse it to find a specific cookie by name:
function getCookie(name) { var pairs = document.cookie.split('; '); for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split('='); if (pair[0] === name) return decodeURIComponent(pair[1]); } return null;}
var theme = getCookie('demo_pref'); // 'dark' or nullNote the decodeURIComponent call — values set with encodeURIComponent must be decoded on read.
Deleting a cookie
Section titled “Deleting a cookie”You cannot delete a cookie by assigning an empty string. You delete a cookie by setting it with Max-Age=0 (or an Expires date in the past):
function deleteCookie(name) { document.cookie = name + '=; Max-Age=0; SameSite=Lax';}
deleteCookie('demo_pref');The complete helper pattern
Section titled “The complete helper pattern”Here is the full get/set/delete pattern used in production code:
function setCookie(name, value, maxAge) { document.cookie = name + '=' + encodeURIComponent(value) + '; Max-Age=' + maxAge + '; SameSite=Lax';}
function getCookie(name) { var pairs = document.cookie.split('; '); for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split('='); if (pair[0] === name) return decodeURIComponent(pair[1]); } return null;}
function deleteCookie(name) { document.cookie = name + '=; Max-Age=0; SameSite=Lax';}