document.cookie, Expiration, & Security FlagsBrowser cookies are small data snippets stored by the web browser on behalf of websites. JavaScript can read and write client-side cookies via document.cookie.
flowchart TD
CookieDecl["Set-Cookie Header / document.cookie"] --> Flags["Security Attributes"]
Flags --> Secure["Secure: Transmit over HTTPS ONLY"]
Flags --> HttpOnly["HttpOnly: Prevent JS access (Protects from XSS)"]
Flags --> SameSite["SameSite=Strict/Lax: Protects from CSRF attacks"]
Flags --> Exp["Expires / Max-Age: Controls persistence duration"]
| Attribute | Syntax Example | Purpose |
|---|---|---|
max-age |
max-age=3600 |
Expiration duration in seconds (3600 = 1 hour). |
expires |
expires=UTC_STRING |
Absolute expiration date string. |
path |
path=/ |
Specifies paths where cookie is accessible. |
SameSite |
SameSite=Lax |
CSRF defense (Strict, Lax, or None). |
Secure |
Secure |
Enforces transmission over HTTPS only. |
// Demonstrating Cookie helper functions for setting, reading, and deleting cookies
// 1. Helper: Set Cookie with Expiration and Security Flags
function setCookie(name, value, days) {
let expires = "";
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = `; expires=${date.toUTCString()}`;
}
// Setting cookie string with Path and SameSite flags
document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}${expires}; path=/; SameSite=Lax`;
}
// 2. Helper: Get Cookie Value by Name
function getCookie(name) {
const nameEQ = encodeURIComponent(name) + "=";
const cookieArray = document.cookie.split(";");
for (let c of cookieArray) {
c = c.trim();
if (c.indexOf(nameEQ) === 0) {
return decodeURIComponent(c.substring(nameEQ.length));
}
}
return null;
}
// 3. Helper: Delete Cookie
function deleteCookie(name) {
// Setting max-age=0 immediately expires the cookie!
document.cookie = `${encodeURIComponent(name)}=; max-age=0; path=/`;
}
// Execution Demo
setCookie("theme_preference", "dark", 7);
console.log(`Read Cookie 'theme_preference': ${getCookie("theme_preference")}`);
HttpOnly for Authentication Tokens: Sensitive auth tokens (JWTs, session IDs) should be set by the server using HttpOnly headers so JavaScript cannot read them, preventing XSS token theft.encodeURIComponent() and decodeURIComponent() to handle special characters safely.max-age=0 (or past expiration date) using the exact same path attribute under which it was originally created.Why should sensitive authentication session cookies be set with the HttpOnly flag from the backend server?
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.