Managing Browser Cookies: Setting, Reading, and Deleting
Setting Cookies
To create a cookie, use the following function:
function createCookie(name, value, daysToExpire = 1) {
const expirationDate = new Date();
expirationDate.setTime(expirationDate.getTime() + daysToExpire * 24 * 60 * 60 * 1000);
const host = window.location.host;
const hostParts = host.split('.');
let cookieString = `${name}=${encodeURIComponent(value)}; expires=${expirationDate.toUTCString()}; path=/`;
if (hostParts.length === 3) {
const domain = '.' + hostParts.slice(1, 3).join('.');
cookieString += `; domain=${domain}`;
}
document.cookie = cookieString;
}
Reading Cookies
To retrieve a cookie value, use this function:
function retrieveCookie(name) {
const pattern = new RegExp(`(^| )${name}=([^;]*)(;|$)`);
const match = document.cookie.match(pattern);
if (match) {
return decodeURIComponent(match[2]);
}
return null;
}
Example Usage:
// Assuming cookie: username=alice; sessionId=abc123
const session = retrieveCookie('sessionId'); // Returns 'abc123'
Deleting Cookies
Too remove a cookie, set its expiration to a past date:
function removeCookie(name) {
const host = window.location.host;
const hostParts = host.split('.');
const pastDate = new Date();
pastDate.setTime(pastDate.getTime() - 24 * 60 * 60 * 1000);
let cookieString = `${name}=; expires=${pastDate.toUTCString()}; path=/`;
if (hostParts.length === 3) {
const domain = '.' + hostParts.slice(1, 3).join('.');
cookieString += `; domain=${domain}`;
}
document.cookie = cookieString;
}
Example Usage:
removeCookie('username'); // Deletes the 'username' cookie
Cookie Properties
Cookies have several important attributes:
- Name: Identifier for the cookie.
- Value: Data stored in the cookie.
- Domain: Specifies which domains can access the cookie.
- Non-top-level domains (e.g., subdomains) can only set cookies for their own domain or parent domains.
- Top-level domains can only set cookies for themselves.
- Cookies set with a top-level domain (e.g.,
.example.com) are accessible across all subdomains.
- Path: Restricts cookie access to specific URL paths within the domain.
- Expires/Max-Age: Defines when the cookie expires. If not set, it defaults to a session cookie (deleeted when the browser closes).
- Size: Storage size of the cookie.
- HttpOnly: When true, the cookie is only accessible via HTTP headers, not through JavaScript.
- Secure: Restricts cookie transmission to HTTPS connections only.