Browser cookies are small key-value pairs (around 4 KB max) stored by the browser and automatically attached to matching HTTP requests sent to your server. JavaScript reads and writes non-HttpOnly cookies through document.cookie.
document.cookie WorksAssigning document.cookie = "theme=dark; path=/; max-age=86400" adds or updates one cookie without erasing other cookies—even though it looks like plain string assignment. Reading document.cookie returns one semicolon-separated string containing all accessible key=value pairs for the current path.
Always wrap cookie values with encodeURIComponent() when writing and decodeURIComponent() when reading so semicolons or spaces never corrupt parsing.
Max-Age=<seconds>: Controls lifetime in seconds (Max-Age=0 deletes a cookie immediately).Path=/: Makes the cookie visible across your entire site instead of only the current folder path.Secure: Sends the cookie over encrypted https:// connections only.SameSite=Lax (or Strict): Helps block Cross-Site Request Forgery (CSRF) attacks.HttpOnly (server-set only): Prevents JavaScript from reading authentication tokens via document.cookie, shielding sessions against XSS.function setCookie(name, value, maxAgeSeconds = 3600) {
const encoded = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
document.cookie = `${encoded}; Path=/; Max-Age=${maxAgeSeconds}; SameSite=Lax`;
}
function getCookie(name) {
const target = `${encodeURIComponent(name)}=`;
const match = document.cookie
.split("; ")
.find((row) => row.startsWith(target));
return match ? decodeURIComponent(match.slice(target.length)) : null;
}
setCookie("ui_density", "compact", 600);
console.log("Read cookie ui_density:", getCookie("ui_density"));
localStorage: Authentication tokens should be set by your backend with HttpOnly; Secure; SameSite=Lax flags so scripts cannot steal them.Path=/ when deleting a cookie: Deleting a cookie requires passing the exact same Path and Domain attributes used when it was created.localStorage instead.localStorage instead of cookies?Use localStorage for client-only preferences like dark mode or draft form text (up to ~5 MB) that your backend server does not need on every HTTP request.
Your backend wisely marked it HttpOnly, which hides the cookie from document.cookie to protect user accounts from Cross-Site Scripting attacks.
Re-assign the same cookie name and Path=/ with Max-Age=0, such as document.cookie = "ui_density=; Path=/; Max-Age=0";.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.