JavaScript Cookies
Cookies are small pieces of data stored in the browser by websites. They are sent to the server with every HTTP request and are commonly used for session management, personalization, and tracking. JavaScript can create, read, and delete cookies using document.cookie.
Setting Cookies
You set a cookie by assigning a string to document.cookie. This does NOT overwrite existing cookies; it adds or updates a single cookie.
// Set a simple cookie
document.cookie = 'username=Alice';
console.log('Set: username=Alice');
// Set cookie with expiration (UTC date string)
const date = new Date();
date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000));
document.cookie = 'theme=dark; expires=' + date.toUTCString() + '; path=/';
console.log('Set: theme=dark (expires in 7 days)');
// Set cookie with max-age (seconds)
document.cookie = 'language=en; max-age=3600; path=/';
console.log('Set: language=en (max-age: 1 hour)');
console.log('\nAll cookies: ' + document.cookie);Reading Cookies
document.cookie returns all cookies for the current page as a single string of semicolon-separated key=value pairs. You need to parse this string to extract specific values.
// document.cookie returns all cookies as one string
// 'username=Alice; theme=dark; language=en'
function getCookie(name) {
const cookies = document.cookie.split('; ');
for (let i = 0; i < cookies.length; i++) {
const parts = cookies[i].split('=');
if (parts[0] === name) {
return decodeURIComponent(parts[1]);
}
}
return null;
}
// Set test cookies
document.cookie = 'user=Alice; path=/';
document.cookie = 'role=admin; path=/';
console.log('All cookies: ' + document.cookie);
console.log('user: ' + getCookie('user'));
console.log('role: ' + getCookie('role'));
console.log('missing: ' + getCookie('missing'));Cookie Parameters
Cookies have several parameters that control their behavior: expiration, path, domain, secure flag, and SameSite attribute.
| Parameter | Description | Example |
|---|---|---|
| expires | UTC date when cookie expires | expires=Thu, 01 Jan 2025 00:00:00 UTC |
| max-age | Seconds until cookie expires | max-age=3600 |
| path | URL path the cookie belongs to | path=/ |
| domain | Domain the cookie belongs to | domain=example.com |
| secure | Only send over HTTPS | secure |
| SameSite | Cross-site request control | SameSite=Strict |
// Full cookie with all parameters
const cookieString = [
'sessionId=abc123',
'expires=' + new Date(2025, 11, 31).toUTCString(),
'path=/',
'domain=example.com',
'secure',
'SameSite=Strict'
].join('; ');
console.log('Full cookie: ' + cookieString);
console.log('\nSameSite options:');
console.log(' Strict - only same-site requests');
console.log(' Lax - safe cross-site (default)');
console.log(' None - all requests (requires secure)');Deleting Cookies
To delete a cookie, set its expiration date to a date in the past. You must use the same path and domain as when the cookie was created.
// Delete a cookie by setting it to expired
function deleteCookie(name) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/';
}
// Set a cookie
document.cookie = 'temp=value; path=/';
console.log('Before delete: ' + document.cookie);
// Delete the cookie
deleteCookie('temp');
console.log('After delete: ' + document.cookie);
// Can also use max-age=0
document.cookie = 'another=test; path=/';
document.cookie = 'another=; max-age=0; path=/';
console.log('After max-age=0: ' + document.cookie);Cookies vs localStorage
Cookies and localStorage both store data in the browser, but they serve different purposes and have different characteristics.
| Feature | Cookies | localStorage |
|---|---|---|
| Size limit | ~4 KB per cookie | ~5-10 MB |
| Sent to server | Yes (every request) | No |
| Expiration | Configurable | Never (manual) |
| API | document.cookie (string) | getItem/setItem |
| Scope | Per domain + path | Per origin |
| Security | HttpOnly, Secure, SameSite | Accessible to all JS |
| Use case | Authentication, sessions | User preferences, cache |
// Use COOKIES for:
console.log('Cookies are best for:');
console.log(' - Authentication tokens (HttpOnly)');
console.log(' - Session management');
console.log(' - Data needed by the server');
// Use LOCALSTORAGE for:
console.log('\nlocalStorage is best for:');
console.log(' - User preferences (theme, language)');
console.log(' - Client-side cache');
console.log(' - Data NOT needed by the server');
console.log(' - Larger data (up to 5-10 MB)');
console.log('\nSecurity note:');
console.log(' HttpOnly cookies cannot be read by JS');
console.log(' Use for auth tokens to prevent XSS theft');