Skip to content

Reading and Writing Cookies

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 untouched

This 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.

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 cookie
document.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.

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 null

Note the decodeURIComponent call — values set with encodeURIComponent must be decoded on read.

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');

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';
}
Browser Storage
What does reading document.cookie return?
How do you delete a cookie using document.cookie?
You write document.cookie = "lang=en; SameSite=Lax". What happens to existing cookies?