JS Cookies
JavaScript Cookies: Reading, Writing, and Security Flags
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.
How document.cookie Works
Assigning 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.
Essential Security Attributes
Max-Age=<seconds>: Controls lifetime in seconds (Max-Age=0deletes a cookie immediately).Path=/: Makes the cookie visible across your entire site instead of only the current folder path.Secure: Sends the cookie over encryptedhttps://connections only.SameSite=Lax(orStrict): Helps block Cross-Site Request Forgery (CSRF) attacks.HttpOnly(server-set only): Prevents JavaScript from reading authentication tokens viadocument.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"));
Common Mistakes to Avoid
- Storing sensitive JWTs or session IDs in JS-readable cookies or
localStorage: Authentication tokens should be set by your backend withHttpOnly; Secure; SameSite=Laxflags so scripts cannot steal them. - Forgetting
Path=/when deleting a cookie: Deleting a cookie requires passing the exact samePathandDomainattributes used when it was created. - Putting large JSON objects in cookies: Cookies travel on every HTTP header request and max out near 4 KB; store UI preferences in
localStorageinstead.
Frequently Asked Questions
When should I use 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.
Why can't JavaScript read my session cookie?
Your backend wisely marked it HttpOnly, which hides the cookie from document.cookie to protect user accounts from Cross-Site Scripting attacks.
How do I delete a cookie from JavaScript?
Re-assign the same cookie name and Path=/ with Max-Age=0, such as document.cookie = "ui_density=; Path=/; Max-Age=0";.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.