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";

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