Cookies in JavaScript

A comprehensive guide to working with cookies in JavaScript, covering cookie creation, setting, reading, and deletion.

Last updated: 2024-12-29

Cookies are a widely used mechanism in web development for storing and tracking user information. This guide covers all aspects of working with cookies in JavaScript.

What are Cookies?

Cookies are small pieces of data sent from a website and stored on the user's computer by the user's web browser. They are designed to be a reliable mechanism for websites to remember stateful information or to record the user's browsing activity.

Creating and Setting Cookies

In JavaScript, cookies are created and set using the document.cookie property:

function setCookie(name, value, days) {
    let expires = "";
    if (days) {
        const date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}

// Usage
setCookie("username", "John Doe", 7);

This function takes the cookie name, value, and expiration time in days as parameters.

Reading Cookies

To read cookies, we need to parse the document.cookie property:

function getCookie(name) {
    const nameEQ = name + "=";
    const ca = document.cookie.split(';');
    for(let i=0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

// Usage
const username = getCookie("username");
console.log(username);  // "John Doe"

Modifying Cookies

To modify a cookie, simply set it again with the new value:

setCookie("username", "Jane Doe", 7);  // Updates the "username" cookie

Deleting Cookies

To delete a cookie, set its expiration date to a past date:

function deleteCookie(name) {
    document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

// Usage
deleteCookie("username");

Cookies have several important attributes:

  1. Expires/Max-Age: Defines when the cookie should expire.
  2. Domain: Specifies which domains the cookie should be sent to.
  3. Path: Indicates the path that must exist in the requested URL for the browser to send the Cookie header.
  4. Secure: Ensures the cookie is only transmitted over HTTPS.
  5. HttpOnly: Prevents JavaScript from accessing the cookie.
  6. SameSite: Controls how cookies are sent with cross-site requests.

Example:

function setAdvancedCookie(name, value, options = {}) {
    options = {
        path: '/',
        ...options
    };

    if (options.expires instanceof Date) {
        options.expires = options.expires.toUTCString();
    }

    let updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value);

    for (let optionKey in options) {
        updatedCookie += "; " + optionKey;
        let optionValue = options[optionKey];
        if (optionValue !== true) {
            updatedCookie += "=" + optionValue;
        }
    }

    document.cookie = updatedCookie;
}

// Usage
setAdvancedCookie("user", "John", {
    'max-age': 3600,
    'secure': true,
    'samesite': 'Strict'
});

Security Considerations

Security is crucial when working with cookies:

  1. Storing sensitive information: Never store passwords or other critical data in cookies.
  2. Protection against XSS (Cross-Site Scripting) attacks: Always sanitize user input.
  3. Protection against CSRF (Cross-Site Request Forgery) attacks: Use CSRF tokens.
// XSS protection
function sanitize(string) {
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#x27;',
        "/": '&#x2F;',
    };
    const reg = /[&<>"'/]/ig;
    return string.replace(reg, (match)=>(map[match]));
}

// Usage
const userInput = "<script>alert('XSS');</script>";
setCookie("userInput", sanitize(userInput), 1);

Cookies and GDPR

Under GDPR (General Data Protection Regulation) rules, you need to get user consent before using cookies:

function setCookieConsent() {
    if (getCookie('cookieConsent') !== 'true') {
        const consent = confirm("Our website uses cookies. Do you consent?");
        if (consent) {
            setCookie('cookieConsent', 'true', 365);
        }
    }
}

// Call on page load
window.onload = setCookieConsent;

Alternatives to Cookies

Alternatives to cookies include:

  1. Web Storage (localStorage and sessionStorage)
  2. IndexedDB
  3. WebSQL (deprecated)

Example using localStorage:

// Storing data
localStorage.setItem('username', 'John Doe');

// Reading data
const username = localStorage.getItem('username');

// Removing data
localStorage.removeItem('username');

Best Practices

  1. Only store necessary information in cookies.
  2. Set expiration dates for cookies.
  3. Use the Secure and HttpOnly flags.
  4. Encrypt or sign cookies.
  5. Comply with GDPR requirements.
  6. Inform users about your cookie policy.

Conclusion

Cookies are a useful tool for web applications, allowing for the storage and tracking of user information. However, it's crucial to use them correctly and securely. By applying the methods and best practices outlined in this guide, you can effectively and safely use cookies in your JavaScript applications.