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.

Creating Cookies
// 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.

Reading and Parsing Cookies
// 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.

ParameterDescriptionExample
expiresUTC date when cookie expiresexpires=Thu, 01 Jan 2025 00:00:00 UTC
max-ageSeconds until cookie expiresmax-age=3600
pathURL path the cookie belongs topath=/
domainDomain the cookie belongs todomain=example.com
secureOnly send over HTTPSsecure
SameSiteCross-site request controlSameSite=Strict
Cookie Parameters
// 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.

Deleting Cookies
// 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.

FeatureCookieslocalStorage
Size limit~4 KB per cookie~5-10 MB
Sent to serverYes (every request)No
ExpirationConfigurableNever (manual)
APIdocument.cookie (string)getItem/setItem
ScopePer domain + pathPer origin
SecurityHttpOnly, Secure, SameSiteAccessible to all JS
Use caseAuthentication, sessionsUser preferences, cache
When to Use Which
// 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');
📝 Note: For authentication, always use HttpOnly cookies (set by the server) rather than JavaScript-accessible cookies or localStorage. HttpOnly cookies cannot be accessed by JavaScript, making them resistant to XSS attacks. The SameSite attribute helps prevent CSRF attacks.
Exercise:
How do you delete a cookie in JavaScript?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.