Browser Storage and State ManagementLesson 5.2
How to read and write browser cookies with JavaScript
document.cookie, cookie syntax, expires, max-age, path, Secure flag, HttpOnly, SameSite, reading cookies, deleting cookies
Browser Cookies
Cookies are key-value pairs stored by the browser and automatically sent with every HTTP request to the matching domain. They are used for authentication tokens, sessions, and tracking.
// Write a cookie
document.cookie = 'username=alice; max-age=3600; path=/';
// Write another — does NOT overwrite others
document.cookie = 'theme=dark; max-age=86400; path=/';
// Read all cookies (one string)
console.log(document.cookie); // 'username=alice; theme=dark'
// Delete a cookie — set max-age to 0
document.cookie = 'username=; max-age=0; path=/';Parsing Cookies
function getCookie(name) {
const entry = document.cookie
.split('; ')
.find(row => row.startsWith(name + '='));
return entry ? entry.split('=')[1] : null;
}Security Attributes
Secure sends the cookie over HTTPS only. HttpOnly prevents JavaScript access entirely — set server-side for auth tokens. SameSite=Strict blocks cross-site request inclusion, mitigating CSRF attacks. Never store sensitive data in cookies accessible to JavaScript.
