Skip to content

JavaScript Cookies

JavaScript Client-Side Storage: Cookies and Web Storage

Section titled “JavaScript Client-Side Storage: Cookies and Web Storage”

JavaScript provides several ways to store user information and application data on the client-side (in the user’s browser). The traditional method is cookies, while modern browsers offer the Web Storage API (localStorage and sessionStorage) which is often simpler for many use cases.

Cookies are small pieces of data, stored as text files on the user’s computer by their web browser. They are associated with a specific website.

Originally, cookies were designed to help websites remember information about a user across multiple page views or visits, as HTTP is a stateless protocol (meaning each request is independent and the server doesn’t inherently remember past interactions).

  • When a user visits a web page, information (like a username or preferences) can be stored in a cookie.
  • The next time the user visits that page (or another page on the same domain), the browser sends the relevant cookies back to the server, allowing the website to “remember” the user or their settings.

Cookies are saved as name-value pairs, e.g., username=john_doe.

While JavaScript can interact with cookies, it’s important to note that cookies are sent with every HTTP request to the domain they belong to, which can impact performance if cookies are large or numerous.

JavaScript can create, read, and delete cookies using the document.cookie property. However, the API is somewhat rudimentary.

To create or update a cookie, you assign a string to document.cookie with the name-value pair and optional attributes like expires, max-age, path, domain, secure, and samesite.

// Basic cookie
document.cookie = "username=john_doe";
// Cookie with an expiry date (UTC) and path
const expiryDate = new Date();
expiryDate.setTime(expiryDate.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days from now
document.cookie = `userId=123; expires=${expiryDate.toUTCString()}; path=/`;
// Cookie with max-age (in seconds), secure, and samesite attributes
// 'secure' means the cookie is only sent over HTTPS
// 'samesite=strict' helps prevent CSRF attacks
document.cookie = "sessionToken=abcxyz; max-age=86400; path=/; secure; samesite=strict";

Important cookie attributes:

  • expires=UTCString: Sets an expiry date. If omitted, it’s a session cookie (deleted when browser closes).
  • max-age=seconds: Preferred over expires. Sets expiry time in seconds from now.
  • path=pathValue: Specifies the URL path for which the cookie is valid (e.g., /, /app).
  • domain=domainValue: Specifies the domain for which the cookie is valid.
  • secure: If present, cookie is only sent over HTTPS.
  • samesite=Strict|Lax|None: Controls cross-site request behavior for CSRF protection.

Reading document.cookie returns a string containing all accessible cookies for the current document, semi-colon separated (e.g., cookie1=value1; cookie2=value2). You’ll need to parse this string to get a specific cookie’s value.

const allCookies = document.cookie;
console.log(allCookies);

To delete a cookie, you set its expires attribute to a past date or max-age to 0 or a negative number. You must also specify the same path and domain attributes that were used when the cookie was set.

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
// or using max-age
document.cookie = "userId=; max-age=0; path=/";

Because document.cookie API is low-level, helper functions are often used:

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();
}
// Encode value to handle special characters
document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}
function getCookie(name) {
const nameEQ = encodeURIComponent(name) + "=";
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;
}
function deleteCookie(name) {
document.cookie = encodeURIComponent(name) + '=; Max-Age=-99999999; path=/';
}
// Usage:
// setCookie("userPreference", "darkMode", 30);
// const pref = getCookie("userPreference");
// if (pref === "darkMode") { /* apply dark mode */ }
// deleteCookie("userPreference");

Modern Alternative: Web Storage API (localStorage and sessionStorage)

Section titled “Modern Alternative: Web Storage API (localStorage and sessionStorage)”

For many client-side storage needs that don’t require data to be sent to the server with every request, the Web Storage API is a more modern and often simpler solution. It offers significantly more storage capacity (typically 5-10MB per origin) compared to cookies (around 4KB).

Stores data with no expiration date. The data remains available even after the browser window is closed and reopened, until explicitly deleted by JavaScript or the user.

// Storing data
localStorage.setItem('theme', 'dark');
localStorage.setItem('user', JSON.stringify({ name: 'Alice', id: 1 }));
// Retrieving data
const theme = localStorage.getItem('theme');
const user = JSON.parse(localStorage.getItem('user'));
console.log(theme); // "dark"
console.log(user.name); // "Alice"
// Removing a specific item
localStorage.removeItem('theme');
// Clearing all items for the origin
// localStorage.clear();

Stores data for the duration of the current browser session. The data is cleared when the tab or browser window is closed.

// Storing data
sessionStorage.setItem('tempData', 'This will be gone after session ends');
// Retrieving data
const tempData = sessionStorage.getItem('tempData');
console.log(tempData);

Key differences between Cookies and Web Storage:

  • Server Interaction: Cookies are sent with every HTTP request to their domain. Web Storage data is not automatically sent to the server.
  • Storage Capacity: Web Storage (5-10MB) > Cookies (~4KB).
  • API Simplicity: Web Storage API (setItem, getItem, removeItem) is generally easier to use than parsing document.cookie.
  • Data Types: Web Storage stores only strings. For objects or arrays, use JSON.stringify() to store and JSON.parse() to retrieve.
  • Accessibility: Cookies can be accessed by both server-side and client-side scripts (unless HttpOnly flag is set). Web Storage is purely client-side.
Choose wisely: Use cookies when data needs to be sent to the server with requests (e.g., session IDs). Use localStorage for persistent client-side storage (e.g., user preferences, offline data). Use sessionStorage for temporary session-specific data (e.g., form data before submission).