Managing Cookies in JavaScript: Set, Retrieve, Update
Cookies remain one of the fundamental mechanisms for storing small pieces of information in the browser. They support authentication sessions, user preferences, and analytics features. Even as modern APIs like localStorage, sessionStorage, and IndexedDB have become popular, cookies continue to play a central role—especially when state must persist across browser tabs and be sent to the server automatically.
This article provides a clear, practical explanation of how cookies work in JavaScript, how to manipulate them safely, and how to incorporate modern “Secure”, “HttpOnly”, and “SameSite” attributes to avoid security pitfalls.
1. What Cookies Are and How Browsers Handle Them
A cookie is a key–value pair stored in the browser. Whenever a request is made to a domain, cookies belonging to that domain are automatically included in the request headers:
Cookie: username=JohnDoe; theme=darkJavaScript interacts with cookies exclusively through the document.cookie property. Cookies set by JavaScript are available only on the client side unless explicitly configured for server usage.
2. Creating Cookies in JavaScript
Setting cookies involves assigning a formatted string to document.cookie:
document.cookie =
"username=JohnDoe; expires=Fri, 12 Jan 2025 12:00:00 UTC; path=/";Key components of the cookie string
- username=JohnDoe — the stored key–value pair
- expires — when the cookie should expire; without this, it becomes a session cookie
- path — restricts access to specific paths;
/makes it site‑wide
Optional but recommended attributes
- Secure — restricts cookie transmission to HTTPS
- SameSite — controls cross‑site request behavior (
Strict,Lax, orNone) - HttpOnly — prevents JavaScript from accessing the cookie (cannot be set via JS, only server-side)
A more complete and modern example:
document.cookie =
"sessionId=abc123; expires=Fri, 12 Jan 2025 12:00:00 UTC; path=/; Secure; SameSite=Lax";3. Retrieving Cookies
document.cookie returns a semicolon‑separated string of all available cookies:
console.log(document.cookie);
// Example: "username=JohnDoe; theme=dark"To extract specific values, you must parse this string manually or with a helper function.
A robust cookie retrieval helper
function getCookie(name) {
const cookies = document.cookie.split("; ");
for (const cookie of cookies) {
const [key, value] = cookie.split("=");
if (key === name) return value;
}
return null;
}Usage:
console.log(getCookie("username")); // "JohnDoe"This approach handles missing cookies gracefully.
4. Updating Cookies
A cookie is updated simply by redefining it with the same name:
document.cookie =
"username=JaneDoe; expires=Fri, 12 Jan 2025 12:00:00 UTC; path=/";Cookies are overwritten when they share:
- the same name
- the same path
- the same domain
If any of these differ, they are treated as separate cookies.
5. Deleting Cookies Properly
To delete a cookie, set its expiration date in the past:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";Deleting only works when the deletion cookie uses the same path and domain as the original.
6. Best Practices for Cookie Management
Avoid storing sensitive data
Cookies are sent automatically with each request and can be intercepted if not configured securely.
Prefer Secure cookies on production
Only send cookies via HTTPS:
document.cookie = "theme=dark; Secure";Use HttpOnly for authentication cookies
Although JavaScript cannot set HttpOnly, your server should use it to block access from document.cookie.
Use SameSite to prevent CSRF
Example:
document.cookie = "theme=dark; SameSite=Strict";Keep cookie names short
Browsers limit the overall cookie size per domain (typically 4 KB per cookie).
7. Example: Full Set and Retrieve Flow
// Set a cookie
document.cookie =
"theme=dark; expires=Fri, 12 Jan 2025 12:00:00 UTC; path=/; Secure; SameSite=Lax";
// Get a cookie
function getCookie(name) {
const cookies = document.cookie.split("; ");
for (const cookie of cookies) {
const [key, value] = cookie.split("=");
if (key === name) return value;
}
return null;
}
console.log(getCookie("theme")); // "dark"This example illustrates secure handling and retrieval in a realistic environment.
Conclusion
Cookies remain a foundational part of web development, especially when working with user sessions, preferences, and server-side integrations. JavaScript’s document.cookie API is simple but powerful when used correctly. Understanding cookie attributes—especially Secure, HttpOnly, and SameSite—is essential for building secure, predictable, and user-friendly applications.