How to Use document.cookie in JavaScript
This article provides a comprehensive overview of how JavaScript
manages client-side storage through the document.cookie
property. You will learn the mechanics of reading, creating, modifying,
and deleting cookies, as well as the key attributes that govern their
lifecycle and security constraints such as the HttpOnly
flag.
Understanding
document.cookie
The document.cookie property acts as a getter and setter
for the cookies associated with the current document. Unlike standard
JavaScript object properties, assigning a value to
document.cookie does not overwrite the entire cookie jar;
instead, it creates or updates a single cookie key-value pair at a
time.
Writing and Creating Cookies
To create a new cookie or update an existing one, assign a string in
the format name=value to document.cookie. You
can append optional attributes separated by semicolons:
document.cookie = "username=JohnDoe; max-age=3600; path=/; Secure; SameSite=Lax";Key Cookie Attributes
expires/max-age: Defines the expiration date.expiresexpects a UTC date string (expires=Thu, 01 Jan 2026 00:00:00 GMT), whilemax-ageaccepts the cookie lifetime in seconds (max-age=3600). Without either, the cookie is treated as a session cookie and deleted when the browser closes.path: Specifies the URL path that must exist in the requested URL for the browser to send the cookie header. Default is the path of the current document.domain: Defines which hosts can receive the cookie. Default is the current host.Secure: Ensures the cookie is only transmitted over encrypted HTTPS connections.SameSite: Controls cross-site cookie transmission (Strict,Lax, orNone) to protect against Cross-Site Request Forgery (CSRF).
Reading Cookies
Accessing document.cookie returns a single string
containing a semicolon-delimited list of all active key-value pairs
accessible to the current page:
console.log(document.cookie);
// Output: "username=JohnDoe; theme=dark; loggedIn=true"To extract a specific cookie value, parse the string by splitting it:
function getCookie(name) {
const cookies = document.cookie.split('; ');
for (const cookie of cookies) {
const [key, value] = cookie.split('=');
if (key === name) {
return decodeURIComponent(value);
}
}
return null;
}Deleting Cookies
Cookies cannot be removed directly using an explicit delete method.
Instead, set the cookie’s max-age to 0 (or set
its expires attribute to a past date) using the exact same
path and domain parameters defined during its
creation:
document.cookie = "username=; max-age=0; path=/";Security and Limitations
- Storage Limits: Individual cookies cannot exceed 4 KB in size, and browsers limit the total number of cookies stored per domain (typically around 20 to 50).
HttpOnlyFlag: Cookies containing sensitive information (such as session tokens) should be marked with theHttpOnlyflag by the server. These cookies cannot be read or modified via JavaScript’sdocument.cookie, safeguarding them against Cross-Site Scripting (XSS) attacks.