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.
What are Cookies?
Section titled “What are Cookies?”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.
Interacting with Cookies using JavaScript
Section titled “Interacting with Cookies using JavaScript”JavaScript can create, read, and delete cookies using the document.cookie property. However, the API is somewhat rudimentary.
Creating or Updating a Cookie:
Section titled “Creating or Updating a Cookie:”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 cookiedocument.cookie = "username=john_doe";
// Cookie with an expiry date (UTC) and pathconst expiryDate = new Date();expiryDate.setTime(expiryDate.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days from nowdocument.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 attacksdocument.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 overexpires. 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 Cookies:
Section titled “Reading Cookies:”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);Deleting a Cookie:
Section titled “Deleting a Cookie:”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-agedocument.cookie = "userId=; max-age=0; path=/";Helper Functions for Cookies (Example):
Section titled “Helper Functions for Cookies (Example):”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).
localStorage:
Section titled “localStorage:”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 datalocalStorage.setItem('theme', 'dark');localStorage.setItem('user', JSON.stringify({ name: 'Alice', id: 1 }));
// Retrieving dataconst theme = localStorage.getItem('theme');const user = JSON.parse(localStorage.getItem('user'));console.log(theme); // "dark"console.log(user.name); // "Alice"
// Removing a specific itemlocalStorage.removeItem('theme');
// Clearing all items for the origin// localStorage.clear();sessionStorage:
Section titled “sessionStorage:”Stores data for the duration of the current browser session. The data is cleared when the tab or browser window is closed.
// Storing datasessionStorage.setItem('tempData', 'This will be gone after session ends');
// Retrieving dataconst 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 parsingdocument.cookie. - Data Types: Web Storage stores only strings. For objects or arrays, use
JSON.stringify()to store andJSON.parse()to retrieve. - Accessibility: Cookies can be accessed by both server-side and client-side scripts (unless
HttpOnlyflag 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). |
|---|