Modern Cookie Manipulation in JavaScript: From jQuery to Native Solutions

Oct 22, 2025 · Programming · 27 views · 7.8

Keywords: Cookie Manipulation | JavaScript | js-cookie | Web Development | Frontend Technology

Abstract: This comprehensive technical article explores the evolution of cookie manipulation in web development, focusing on the transition from jQuery-dependent plugins to native JavaScript solutions. It provides detailed analysis of the js-cookie library, covering cookie creation, reading, deletion, and advanced configuration options. Through practical code examples and in-depth technical comparisons, the article offers complete guidance and best practices for modern cookie handling in web applications.

The Evolution of Cookie Manipulation

Throughout the history of web development, cookies have served as a crucial mechanism for client-side data storage, with manipulation methods undergoing significant evolution. Early developers often relied on libraries like jQuery to simplify cookie operations, but with the advancement of modern JavaScript ecosystems, lighter and more efficient native solutions have become mainstream.

Core Library for Modern Cookie Operations: js-cookie

The currently recommended approach for cookie manipulation is using the js-cookie library, a pure JavaScript solution that doesn't depend on any framework and provides a concise yet powerful API.

// Basic cookie setting
Cookies.set('username', 'john_doe');

// Setting cookies with expiration
Cookies.set('session_id', 'abc123', { expires: 7 });

// Reading cookies
const userName = Cookies.get('username');
console.log(userName); // Output: 'john_doe'

// Deleting cookies
Cookies.remove('username');

Advanced Configuration Options

The js-cookie library supports comprehensive cookie attribute configurations to meet various complex scenarios:

// Complete cookie configuration example
Cookies.set('preferences', JSON.stringify({
    theme: 'dark',
    language: 'en-US',
    notifications: true
}), {
    expires: 30,           // Expires in 30 days
    path: '/',             // Valid across entire site
    domain: 'example.com', // Specific domain
    secure: true,          // HTTPS only
    sameSite: 'strict'     // Same-site policy
});

Comparison with Traditional jQuery Approach

Although the jQuery-cookie plugin was widely used historically, it has several limitations:

// Traditional jQuery-cookie usage (no longer recommended)
$.cookie('test', 1);
$.cookie('test', 1, { expires: 10 });
$.removeCookie('test');

In comparison, js-cookie offers several advantages: no dependencies, smaller footprint, better browser compatibility, and more active maintenance.

Native JavaScript Implementation

For projects that prefer not to introduce external libraries, cookies can be manipulated directly using native JavaScript:

function createCookie(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 = encodeURIComponent(name) + '=' + 
                     encodeURIComponent(value) + expires + '; path=/';
}

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

function deleteCookie(name) {
    createCookie(name, '', -1);
}

Common Issues and Solutions

In practical development, cookie manipulation can encounter various issues. The cookie auto-restoration problem mentioned in reference article 2 is typically caused by:

Solutions include ensuring that cookie deletion uses exactly the same path and domain attributes as setting, clearing browser cache, and checking for third-party script impacts.

Best Practice Recommendations

Based on years of development experience, we summarize the following best practices for cookie manipulation:

  1. Prefer modern libraries like js-cookie to avoid unnecessary dependencies
  2. Always encode cookie values to prevent special character issues
  3. Set appropriate expiration times to balance user experience and data security
  4. Use secure flags to ensure safe transmission of sensitive information
  5. Regularly review and clean up unnecessary cookies
  6. Consider localStorage or sessionStorage as alternative solutions

Performance and Security Considerations

Cookie manipulation affects not only functionality but also website performance and security:

Future Development Trends

As web standards evolve, cookie technology continues to develop. New proposals like the Cookie Store API aim to provide more modern and powerful cookie manipulation interfaces. Meanwhile, strengthened privacy protection regulations are prompting developers to reconsider cookie usage strategies.

In conclusion, choosing the right cookie manipulation approach is crucial in modern web development. The js-cookie library, with its concise API, dependency-free nature, and well-maintained status, represents the most recommended choice currently available.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.