Skip to content
Education & Software

Mastering How to Use Cookies Set in JavaScript

In this article

Client-side cookie management allows web applications to store small pieces of data directly within the browser, enabling session persistence, user preference tracking, and state management across navigation requests. Understanding how to create, read, update, and secure these textual values is essential for building interactive web interfaces and ensuring compliance with modern security and privacy standards.

Understanding the Fundamentals of Client-Side Cookies

HTTP cookies are small blocks of data created by a web server while a user is browsing a website and placed on the user's computer by the user's web browser. While traditionally managed via server-side HTTP headers, JavaScript provides a straightforward interface to interact with these tokens through the document.cookie property. This string-based API exposes a concatenated list of all cookies accessible to the current document, separated by semicolons and spaces.

Writing to document.cookie does not overwrite the entire collection of cookies stored for that domain unless explicitly structured to do so. Instead, assigning a new string to this property appends or updates an individual cookie based on its unique name and path combination. Reading from it requires parsing the resulting string to extract specific key-value pairs. Because document.cookie combines all accessible values into a single flat string, developers must implement utility logic or parsing algorithms to query individual data points effectively.

Security, scope, and longevity are controlled entirely through attribute flags appended during creation. Without proper attributes, cookies default to a volatile lifecycle that terminates when the browser session closes, and they remain vulnerable to interception or unauthorized script execution. Mastering these attributes is the first step toward implementing robust client-side storage strategies.

Essential Attributes and Syntax for Setting Cookies

Creating a cookie via JavaScript requires assigning a specially formatted string to document.cookie. The fundamental syntax consists of a name-value pair followed by optional semicolon-delimited attributes that dictate behavior, security, and lifetime. Omitting key attributes can introduce severe vulnerabilities or cause the data to expire prematurely.

The basic assignment pattern follows this structure: document.cookie = "username=JohnDoe; expires=Thu, 18 Dec 2026 12:00:00 UTC; path=/";. Every cookie string must begin with a valid identifier and value, URL-encoded to prevent syntax errors caused by special characters, semicolons, or whitespace.

Attribute Purpose Behavior When Omitted
expires / max-age Defines the exact expiration date or relative lifetime in seconds. Becomes a session cookie, deleted when the browser closes.
path Restricts cookie visibility to specific URL paths on the domain. Defaults to the current document's path directory.
domain Specifies which hosts are allowed to receive the cookie. Defaults to the current host, excluding subdomains.
Secure Ensures the cookie is only transmitted over encrypted HTTPS channels. Allowed over insecure HTTP connections.
SameSite Controls cross-site request behavior (Strict, Lax, or None). Modern browsers default to Lax if unspecified.

Understanding how these attributes interact prevents common issues where cookies fail to persist or transmit across expected page routes. The path attribute, for example, is critical; if a cookie is set with a path of /dashboard, it will not be accessible to scripts running on the homepage (/).

Allowing JavaScript and cookies in your browser - SimplePractice Support
Allowing JavaScript and cookies in your browser - SimplePractice Support

How to Write, Read, and Update Cookies in JavaScript

Manipulating cookies programmatically involves three core operations: writing new data, parsing the storage string to read existing values, and updating or deleting specific entries. Because the native API lacks dedicated methods like setItem or getItem found in Web Storage, developers rely on string manipulation techniques.

To write a cookie safely, it is best practice to construct a function that handles URL encoding automatically. This ensures that values containing spaces, equal signs, or non-ASCII characters do not corrupt the cookie string.

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(); } document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/; SameSite=Lax"; }

Reading cookies requires splitting the document.cookie string by semicolons and iterating through the resulting array to match the requested key. Because multiple cookies share the string, finding a substring match without proper tokenization can lead to false positives (e.g., searching for "user" matching "super-user").

function getCookie(name) { const nameEQ = name + "="; const ca = document.cookie.split(';'); for (let i = 0; i < ca.length; i++) { c = ca[i].trim(); if (c.indexOf(nameEQ) === 0) { return decodeURIComponent(c.substring(nameEQ.length, c.length)); } } return null; }

Updating an existing cookie is achieved simply by re-writing it using the exact same name and path, accompanied by a new value or expiration date. Deletion follows the same principle, except the expiration date is set to a timestamp in the past, prompting the browser to purge the record immediately.

Mitigating Security Risks and Cross-Site Scripting (XSS)

Client-side cookies are inherently susceptible to security threats, most notably Cross-Site Scripting (XSS). Because JavaScript running in the browser can read and write to document.cookie, any malicious script injected into the page via vulnerabilities can steal sensitive authentication tokens, session identifiers, or personal data stored within accessible cookies.

To mitigate this risk, sensitive tokens—such as JSON Web Tokens (JWTs) or session identifiers—should never be set or read via JavaScript. Instead, they should be issued by the server using the HttpOnly flag within the Set-Cookie HTTP response header. The HttpOnly attribute completely blocks client-side scripts from accessing the cookie, rendering them immune to theft via XSS, even if an attacker successfully injects malicious script execution.

Set-Cookie: session_id=xyz123; Secure; HttpOnly; SameSite=Strict

When client-side cookies must be used for non-sensitive UI preferences (such as dark mode toggles or language selections), developers must implement strict input sanitization, validate all data before storage, and apply appropriate SameSite configurations to defend against Cross-Site Request Forgery (CSRF) attacks. Utilizing the Secure flag is also mandatory in production environments to ensure data is never transmitted in cleartext over unencrypted networks.

Managing Cookie Size Limits and Alternative Storage Options

Cookies were designed for small pieces of metadata, and browser specifications enforce strict size limits. Most modern web browsers limit individual cookies to a maximum size of 4096 bytes (4 KB) for both the name and the value combined. Additionally, browsers enforce limits on the total number of cookies allowed per domain, often capped around 50 to 180 cookies depending on the user agent. Exceeding these limits causes browsers to silently ignore new cookie writes or evict older entries.

When applications require larger amounts of structured client-side storage, relying on cookies introduces performance overhead because every cookie is automatically transmitted to the server with every HTTP request made to that domain. This unnecessary bandwidth consumption can slow down page load speeds, particularly on mobile networks.

For storing complex data structures, larger datasets, or persistent application state that does not need to be sent to the server with every request, modern web development provides superior alternatives:

  • Web Storage API (localStorage): Offers key-value storage with a capacity of typically 5 MB to 10 MB per origin. Data persists indefinitely until explicitly cleared by script or user action.
  • Session Storage (sessionStorage): Similar to localStorage, but data is scoped strictly to the current browser tab or window session and is wiped when the tab closes.
  • IndexedDB: A low-level transactional database system designed for storing significant amounts of structured data, including files and blobs, with powerful querying capabilities.

Evaluating the specific persistence, scope, and transmission requirements of your application data ensures you select the optimal storage mechanism rather than defaulting to cookies for every use case.

Troubleshooting Common Cookie Implementation Errors

Developers frequently encounter subtle bugs when working with client-side cookies due to misconfigured attributes or scope mismatches. Recognizing these common pitfalls accelerates debugging and ensures predictable behavior across different browsers.

One frequent issue is the failure of a cookie to persist across page refreshes or subdomains. If a cookie is set with an explicit path like /blog, attempts to read it from the root domain / will return null. Similarly, omitting the domain attribute restricts the cookie strictly to the exact host that set it, meaning subdomains like shop.example.com cannot access cookies set by example.com unless the domain attribute is explicitly configured with a leading dot or matching suffix, subject to modern browser security policies.

Another common source of frustration involves the SameSite attribute. Modern browsers enforce strict defaults regarding cross-site requests. If your application embeds resources or interacts with third-party contexts where cookies must be sent across distinct origins, setting SameSite=None is required—but it must be paired with the Secure flag. Omitting Secure when SameSite=None is specified will cause the browser to reject the cookie outright.

Finally, timezone discrepancies can lead to premature cookie expiration. The expires attribute requires a GMT/UTC string formatted via toUTCString(). Utilizing local time strings or improper date math can cause cookies to expire instantly upon creation.

Frequently Asked Questions

How do I delete a cookie using JavaScript?

You delete a cookie by re-assigning its name with an empty value and setting its expires date to a time in the past, such as Thu, 01 Jan 1970 00:00:00 GMT. You must also ensure that the path and domain attributes match the exact parameters used when the cookie was originally created. If any scoping attribute differs, the browser will create a new cookie instead of removing the existing one.

Can JavaScript read HttpOnly cookies?

No, JavaScript cannot read or write cookies configured with the HttpOnly flag. This security restriction is enforced natively by the browser to protect sensitive data, such as session tokens, from being accessed or exfiltrated by Cross-Site Scripting (XSS) attacks. Management of HttpOnly cookies must be handled entirely by the server through HTTP response headers.

Why is my cookie disappearing when I close the browser?

If your cookie disappears upon closing the browser, it was created as a session cookie. Session cookies lack an expires or max-age attribute, instructing the browser to keep them only for the duration of the active browsing session. To persist cookies across browser restarts, you must calculate and append an explicit future expiration date.

What is the maximum size allowed for a single cookie?

The maximum size for a single cookie—including its name, value, and associated attributes—is typically 4096 bytes (4 KB). Browsers also enforce a limit on the total number of cookies a single domain can store, usually ranging between 50 and 180. Exceeding these limits will result in the browser failing to save the cookie or automatically evicting older entries.

How do I handle special characters in cookie values?

Special characters such as semicolons, commas, equals signs, and whitespace can corrupt the structure of a cookie string. You should always wrap cookie values in encodeURIComponent() when writing them via document.cookie and decode them using decodeURIComponent() when reading them back into your application logic.