Skip to main content
โšก Calmops

Cookies: Creation, Reading, and Deletion in JavaScript

Cookies: Creation, Reading, and Deletion in JavaScript

Introduction

Cookies are small pieces of data stored on the client’s browser that can be sent with HTTP requests. They’re useful for storing user preferences, session information, and tracking data. Understanding how to work with cookies is essential for web development. In this article, you’ll learn how to create, read, update, and delete cookies, along with best practices and security considerations.

Understanding Cookies

// Cookies are stored in document.cookie
console.log(document.cookie); // Shows all cookies as a string

// Cookie format: name=value; name2=value2; ...
// Example: "userId=123; theme=dark; language=en"
// Cookie attributes:
// - name: cookie name
// - value: cookie value
// - expires: expiration date
// - max-age: lifetime in seconds
// - path: URL path where cookie is valid
// - domain: domain where cookie is valid
// - secure: only send over HTTPS
// - samesite: CSRF protection (Strict, Lax, None)

Creating Cookies

// Create a simple cookie
document.cookie = "username=John";

// Create a cookie with expiration
const date = new Date();
date.setTime(date.getTime() + (24 * 60 * 60 * 1000)); // 24 hours
document.cookie = `username=John; expires=${date.toUTCString()}`;

// Create a cookie with multiple attributes
document.cookie = "username=John; expires=" + date.toUTCString() + "; path=/; secure; samesite=Strict";
// Set cookie to expire in 7 days
function setCookieWithExpiry(name, value, days) {
  const date = new Date();
  date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
  
  document.cookie = `${name}=${value}; expires=${date.toUTCString()}; path=/`;
}

// Usage
setCookieWithExpiry('userId', '12345', 7);
setCookieWithExpiry('theme', 'dark', 30);
// Create cookie with all attributes
function createCookie(name, value, options = {}) {
  let cookieString = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
  
  if (options.expires) {
    cookieString += `; expires=${options.expires.toUTCString()}`;
  }
  
  if (options.maxAge) {
    cookieString += `; max-age=${options.maxAge}`;
  }
  
  if (options.path) {
    cookieString += `; path=${options.path}`;
  }
  
  if (options.domain) {
    cookieString += `; domain=${options.domain}`;
  }
  
  if (options.secure) {
    cookieString += '; secure';
  }
  
  if (options.sameSite) {
    cookieString += `; samesite=${options.sameSite}`;
  }
  
  document.cookie = cookieString;
}

// Usage
const expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + 7);

createCookie('sessionId', 'abc123', {
  expires: expiryDate,
  path: '/',
  secure: true,
  sameSite: 'Strict'
});

Reading Cookies

// Get a specific cookie value
function getCookie(name) {
  const nameEQ = encodeURIComponent(name) + "=";
  const cookies = document.cookie.split(';');
  
  for (let cookie of cookies) {
    cookie = cookie.trim();
    if (cookie.indexOf(nameEQ) === 0) {
      return decodeURIComponent(cookie.substring(nameEQ.length));
    }
  }
  
  return null;
}

// Usage
const userId = getCookie('userId');
console.log(userId); // Returns the value or null

Get All Cookies

// Get all cookies as an object
function getAllCookies() {
  const cookies = {};
  
  document.cookie.split(';').forEach(cookie => {
    const [name, value] = cookie.trim().split('=');
    if (name) {
      cookies[decodeURIComponent(name)] = decodeURIComponent(value);
    }
  });
  
  return cookies;
}

// Usage
const allCookies = getAllCookies();
console.log(allCookies);
// { userId: '123', theme: 'dark', language: 'en' }
// Check if a cookie exists
function hasCookie(name) {
  return getCookie(name) !== null;
}

// Usage
if (hasCookie('userId')) {
  console.log('User is logged in');
} else {
  console.log('User is not logged in');
}

Updating and Deleting Cookies

// Update a cookie (set with same name)
function updateCookie(name, value, days = 7) {
  const date = new Date();
  date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
  
  document.cookie = `${name}=${value}; expires=${date.toUTCString()}; path=/`;
}

// Usage
updateCookie('theme', 'light', 30);
// Delete a cookie by setting expiration to past
function deleteCookie(name) {
  document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
}

// Usage
deleteCookie('userId');
deleteCookie('theme');

Delete All Cookies

// Delete all cookies
function deleteAllCookies() {
  document.cookie.split(';').forEach(cookie => {
    const name = cookie.split('=')[0].trim();
    if (name) {
      deleteCookie(name);
    }
  });
}

// Usage
deleteAllCookies();

Pattern 1: User Preferences

// Store and retrieve user preferences
class UserPreferences {
  static set(key, value) {
    const date = new Date();
    date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000)); // 1 year
    
    document.cookie = `pref_${key}=${JSON.stringify(value)}; expires=${date.toUTCString()}; path=/`;
  }
  
  static get(key) {
    const value = getCookie(`pref_${key}`);
    return value ? JSON.parse(value) : null;
  }
  
  static remove(key) {
    deleteCookie(`pref_${key}`);
  }
}

// Usage
UserPreferences.set('theme', 'dark');
UserPreferences.set('language', 'en');
UserPreferences.set('fontSize', 14);

console.log(UserPreferences.get('theme')); // 'dark'
console.log(UserPreferences.get('fontSize')); // 14

UserPreferences.remove('theme');

Pattern 2: Session Management

// Session management with cookies
class SessionManager {
  static createSession(userId, sessionData) {
    const sessionId = Math.random().toString(36).substr(2, 9);
    const date = new Date();
    date.setTime(date.getTime() + (60 * 60 * 1000)); // 1 hour
    
    document.cookie = `sessionId=${sessionId}; expires=${date.toUTCString()}; path=/; secure; samesite=Strict`;
    document.cookie = `userId=${userId}; expires=${date.toUTCString()}; path=/; secure; samesite=Strict`;
    
    return sessionId;
  }
  
  static getSession() {
    return {
      sessionId: getCookie('sessionId'),
      userId: getCookie('userId')
    };
  }
  
  static isSessionValid() {
    return getCookie('sessionId') !== null && getCookie('userId') !== null;
  }
  
  static destroySession() {
    deleteCookie('sessionId');
    deleteCookie('userId');
  }
}

// Usage
SessionManager.createSession('user123', {});
console.log(SessionManager.isSessionValid()); // true
console.log(SessionManager.getSession()); // { sessionId: '...', userId: 'user123' }
SessionManager.destroySession();

Pattern 3: Remember Me

// Remember me functionality
class RememberMe {
  static save(email, password) {
    const date = new Date();
    date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000)); // 30 days
    
    // Note: Never store plain passwords in cookies!
    // This is for demonstration only
    document.cookie = `rememberEmail=${email}; expires=${date.toUTCString()}; path=/`;
    document.cookie = `rememberMe=true; expires=${date.toUTCString()}; path=/`;
  }
  
  static retrieve() {
    if (getCookie('rememberMe') === 'true') {
      return {
        email: getCookie('rememberEmail'),
        rememberMe: true
      };
    }
    return null;
  }
  
  static clear() {
    deleteCookie('rememberEmail');
    deleteCookie('rememberMe');
  }
}

// Usage
RememberMe.save('[email protected]', 'password');
const remembered = RememberMe.retrieve();
if (remembered) {
  console.log('Auto-fill email:', remembered.email);
}

Pattern 4: Tracking and Analytics

// Simple tracking with cookies
class Analytics {
  static trackPageView() {
    const visitCount = parseInt(getCookie('visitCount') || '0') + 1;
    const date = new Date();
    date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000)); // 1 year
    
    document.cookie = `visitCount=${visitCount}; expires=${date.toUTCString()}; path=/`;
    
    if (visitCount === 1) {
      document.cookie = `firstVisit=${new Date().toISOString()}; expires=${date.toUTCString()}; path=/`;
    }
  }
  
  static getAnalytics() {
    return {
      visitCount: parseInt(getCookie('visitCount') || '0'),
      firstVisit: getCookie('firstVisit')
    };
  }
}

// Usage
Analytics.trackPageView();
console.log(Analytics.getAnalytics());

Real-World Examples

Example 1: Theme Switcher

// Theme switcher with cookie persistence
class ThemeSwitcher {
  constructor() {
    this.themes = ['light', 'dark', 'auto'];
    this.currentTheme = this.loadTheme();
    this.applyTheme();
  }
  
  loadTheme() {
    const saved = getCookie('theme');
    return saved || 'light';
  }
  
  saveTheme(theme) {
    if (this.themes.includes(theme)) {
      const date = new Date();
      date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
      
      document.cookie = `theme=${theme}; expires=${date.toUTCString()}; path=/`;
      this.currentTheme = theme;
      this.applyTheme();
    }
  }
  
  applyTheme() {
    document.documentElement.setAttribute('data-theme', this.currentTheme);
  }
  
  toggleTheme() {
    const currentIndex = this.themes.indexOf(this.currentTheme);
    const nextTheme = this.themes[(currentIndex + 1) % this.themes.length];
    this.saveTheme(nextTheme);
  }
}

// Usage
const themeSwitcher = new ThemeSwitcher();
document.getElementById('themeToggle').addEventListener('click', () => {
  themeSwitcher.toggleTheme();
});

Example 2: Login Form with Remember Me

// Login form with remember me
document.getElementById('loginForm').addEventListener('submit', function(e) {
  e.preventDefault();
  
  const email = document.getElementById('email').value;
  const password = document.getElementById('password').value;
  const rememberMe = document.getElementById('rememberMe').checked;
  
  // Authenticate user
  authenticateUser(email, password).then(user => {
    // Create session
    const date = new Date();
    date.setTime(date.getTime() + (60 * 60 * 1000)); // 1 hour
    
    document.cookie = `userId=${user.id}; expires=${date.toUTCString()}; path=/; secure`;
    document.cookie = `sessionToken=${user.token}; expires=${date.toUTCString()}; path=/; secure`;
    
    // Save remember me preference
    if (rememberMe) {
      const rememberDate = new Date();
      rememberDate.setTime(rememberDate.getTime() + (30 * 24 * 60 * 60 * 1000));
      
      document.cookie = `rememberEmail=${email}; expires=${rememberDate.toUTCString()}; path=/`;
    }
    
    // Redirect to dashboard
    window.location.href = '/dashboard';
  });
});

// Pre-fill email if remembered
window.addEventListener('load', () => {
  const rememberEmail = getCookie('rememberEmail');
  if (rememberEmail) {
    document.getElementById('email').value = rememberEmail;
    document.getElementById('rememberMe').checked = true;
  }
});

Example 3: Notification Preferences

// Store notification preferences
class NotificationPreferences {
  static save(preferences) {
    const date = new Date();
    date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
    
    document.cookie = `notifPrefs=${JSON.stringify(preferences)}; expires=${date.toUTCString()}; path=/`;
  }
  
  static load() {
    const prefs = getCookie('notifPrefs');
    return prefs ? JSON.parse(prefs) : this.getDefaults();
  }
  
  static getDefaults() {
    return {
      email: true,
      push: true,
      sms: false,
      marketing: false
    };
  }
  
  static update(key, value) {
    const prefs = this.load();
    prefs[key] = value;
    this.save(prefs);
  }
}

// Usage
NotificationPreferences.update('email', false);
console.log(NotificationPreferences.load());
// Security best practices

// 1. Always use secure flag for sensitive data
document.cookie = "sessionId=abc123; secure; samesite=Strict; path=/";

// 2. Use httpOnly flag (server-side) for sensitive cookies
// This prevents JavaScript from accessing the cookie

// 3. Encode sensitive data
function setSecureCookie(name, value) {
  const encoded = btoa(JSON.stringify(value)); // Base64 encode
  const date = new Date();
  date.setTime(date.getTime() + (60 * 60 * 1000));
  
  document.cookie = `${name}=${encoded}; expires=${date.toUTCString()}; secure; samesite=Strict; path=/`;
}

function getSecureCookie(name) {
  const value = getCookie(name);
  return value ? JSON.parse(atob(value)) : null;
}

// 4. Never store passwords in cookies
// 5. Use HTTPS for all cookie transmission
// 6. Set appropriate expiration times
// 7. Use SameSite attribute to prevent CSRF

Common Mistakes to Avoid

Mistake 1: Not Encoding Values

// โŒ Wrong - Special characters break cookie
document.cookie = "data=hello world; path=/";

// โœ… Correct - Encode values
document.cookie = `data=${encodeURIComponent('hello world')}; path=/`;

Mistake 2: Storing Sensitive Data

// โŒ Wrong - Never store passwords
document.cookie = "password=myPassword123; path=/";

// โœ… Correct - Store only session tokens
document.cookie = "sessionToken=abc123; secure; samesite=Strict; path=/";

Mistake 3: Not Setting Path

// โŒ Wrong - Cookie available everywhere
document.cookie = "userId=123";

// โœ… Correct - Limit cookie scope
document.cookie = "userId=123; path=/";

Mistake 4: Forgetting to Delete

// โŒ Wrong - Cookie persists
document.cookie = "tempData=value";

// โœ… Correct - Delete when done
deleteCookie('tempData');

Summary

Cookies provide client-side storage:

  • Create cookies with document.cookie
  • Set expiration dates for persistence
  • Use secure and samesite flags for security
  • Encode values to handle special characters
  • Always check for cookie existence
  • Delete cookies by setting past expiration
  • Never store sensitive data like passwords
  • Use httpOnly flag (server-side) for sensitive cookies
  • Consider localStorage/sessionStorage as alternatives
  • Always validate cookie data on the server

Next Steps

Continue your learning journey:

Comments