Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Managing Browser Cookies: Setting, Reading, and Deleting

Tech 1

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.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.