Managing Cookies in JavaScript: Creation, Retrieval, and Deletion

Browser cookies can be managed directly through the document.cookie API. Below are implementations for creating, reading, and removing cookies, including handling specific cross-domain issues.

Creating a Cookie

The writeCookie function constructs a cookie string with an optional expiration date. Using encodeURIComponent ensures the value is safely encoded, while toUTCString formats the expiry timestamp correctly.

function writeCookie(key, value, daysToLive) {
    let cookieString = key + "=" + encodeURIComponent(value);
    
    if (daysToLive) {
        const expirationDate = new Date();
        expirationDate.setTime(expirationDate.getTime() + (daysToLive * 24 * 60 * 60 * 1000));
        cookieString += ";expires=" + expirationDate.toUTCString();
    }
    
    cookieString += ";path=/";
    document.cookie = cookieString;
}

Reading a Cookie

To retrieve a value, parse the existing cookie string. A regular expression offers a concise way to locate the specific key.

function readCookie(key) {
    const pattern = new RegExp("(^| )" + key + "=([^;]*)");
    const matches = document.cookie.match(pattern);
    
    if (matches) {
        return decodeURIComponent(matches[2]);
    }
    return null;
}

Deleting a Cookie

Deletion is performed by setting the cookie's expiration date to the past. A critical consideration involves the domain attribute. If a cookie was created on a parent domain (e.g., .example.com), attempts to delete it from a subdomain (e.g., sub.example.com) will fail unless the exact domain is specified in the removal string.

function removeCookie(key, domain) {
    let cookieString = key + "=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/";
    
    if (domain) {
        cookieString += ";domain=" + domain;
    }
    
    document.cookie = cookieString;
}

For example, if a backend sets a cookie on .site.com, the frontend must pass this domain parameter to successfully clear it:

// Standard deletion (may fail for cross-domain cookies)
removeCookie('session_id');

// Explicit domain deletion (required if cookie is set on parent domain)
removeCookie('session_id', '.site.com');

Tags: javascript Cookie web development frontend

Posted on Thu, 25 Jun 2026 16:20:56 +0000 by 8mycsh