NeuroAgent

jQuery Cookie Tutorial: Set, Get, and Delete

Learn how to set, get, and delete cookies using jQuery with our complete tutorial. Includes code examples, best practices, and the jQuery cookie plugin for easy cookie management.

Question

How do I set and unset a cookie using jQuery? For example, how do I create a cookie named test and set its value to 1?

NeuroAgent

To set a cookie named “test” with value “1” using jQuery, you can use the jQuery cookie plugin with $.cookie("test", 1), and to unset it, use $.removeCookie("test"). This approach provides a simple, standardized way to manage browser cookies with built-in support for expiration, path, domain, and security options. The cookie plugin handles all the complexities of cookie manipulation while maintaining cross-browser compatibility and proper encoding.

The most common and reliable approach for cookie manipulation with jQuery is to use a dedicated cookie plugin. The jQuery Cookie plugin provides a simple interface for reading, writing, and deleting cookies.

To get started, you’ll need to include both jQuery and the cookie plugin in your HTML:

html
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>

Once loaded, setting a cookie becomes straightforward. For your specific example of creating a cookie named “test” with value “1”:

javascript
$.cookie("test", 1);

This basic syntax sets a cookie that persists until the browser session ends. The plugin automatically handles URL encoding and proper formatting of the cookie string, making it more reliable than manual cookie manipulation.

The jQuery Cookie plugin is widely used and well-documented, making it a safe choice for production applications. According to Stack Overflow, this has been the standard approach for jQuery-based cookie manipulation.


Setting Cookies with Options

For more control over your cookies, the jQuery plugin supports various options that can be passed as a third parameter. These options include expiration time, path, domain, and security settings.

Here’s how to set a cookie with multiple options:

javascript
$.cookie("test", 1, {
    expires: 7,           // Cookie expires in 7 days
    path: "/",            // Cookie is available across the entire site
    domain: "example.com", // Cookie is available for this domain
    secure: true          // Cookie is only sent over HTTPS
});

Common Cookie Options

  • expires: Can be a number (days from now) or a Date object
  • path: String specifying the path the cookie is available for (default is current path)
  • domain: String specifying the domain the cookie is available for
  • secure: Boolean indicating if the cookie should only be sent over HTTPS
  • raw: Boolean indicating if the cookie value should not be URI encoded

As shown in the SitePoint tutorial, you can create cookies with different expiration times:

javascript
// Cookie that expires in 10 days
$.cookie("test", 1, { expires: 10 });

// Cookie that expires at a specific date
var expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + 7);
$.cookie("test", 1, { expires: expiryDate });

Using the max-age option provides an alternative to expires:

javascript
// Set cookie to expire in 30 days (30 * 24 * 60 * 60 seconds)
document.cookie = "test=1; max-age=" + (30 * 24 * 60 * 60) + "; path=/";

Reading cookie values is just as simple as setting them. To retrieve the value of a previously set cookie:

javascript
var cookieValue = $.cookie("test");
console.log(cookieValue); // Outputs: 1

If you try to read a cookie that doesn’t exist, the plugin returns undefined:

javascript
var nonExistentCookie = $.cookie("nonexistent");
console.log(nonExistentCookie); // Outputs: undefined

The SitePoint documentation explains that reading cookies is straightforward - you simply call $.cookie() with the cookie name as the only parameter.

For more complex scenarios, you can read all cookies at once:

javascript
var allCookies = $.cookie();
console.log(allCookies); // Returns an object with all cookies

This returns an object where keys are cookie names and values are the corresponding cookie values, making it easy to work with multiple cookies programmatically.


Unsetting or Deleting Cookies

To remove a cookie, you use the $.removeCookie() method. This is the proper way to unset cookies using the jQuery plugin:

javascript
$.removeCookie("test");

When removing cookies, it’s important to match the same path and domain that were used when the cookie was created, otherwise the removal might not work:

javascript
// Remove cookie with specific path
$.removeCookie("test", { path: "/" });

// Remove cookie with domain
$.removeCookie("test", { domain: "example.com" });

According to the Stack Overflow answer, the standard pattern is:

javascript
// Set cookie
$.cookie("test", 1);

// Delete cookie
$.removeCookie("test");

Alternative JavaScript Approach

If you prefer not to use a plugin, you can work with cookies using native JavaScript, but this requires more manual handling:

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

// Get cookie
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var 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;
}

// Delete cookie
function eraseCookie(name) {
    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
}

Complete Example Implementation

Here’s a complete, practical example that demonstrates setting, getting, and removing cookies using jQuery:

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery Cookie Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
</head>
<body>
    <h1>jQuery Cookie Demo</h1>
    <button id="setCookie">Set Cookie (test=1)</button>
    <button id="getCookie">Get Cookie Value</button>
    <button id="removeCookie">Remove Cookie</button>
    <div id="result"></div>

    <script>
        $(document).ready(function() {
            // Set cookie button
            $("#setCookie").click(function() {
                $.cookie("test", 1, { expires: 7 });
                $("#result").html("Cookie 'test' has been set with value 1");
            });

            // Get cookie button
            $("#getCookie").click(function() {
                var value = $.cookie("test");
                if (value !== undefined) {
                    $("#result").html("Cookie 'test' value: " + value);
                } else {
                    $("#result").html("Cookie 'test' does not exist");
                }
            });

            // Remove cookie button
            $("#removeCookie").click(function() {
                $.removeCookie("test");
                $("#result").html("Cookie 'test' has been removed");
            });
        });
    </script>
</body>
</html>

This interactive example demonstrates all three operations:

  • Setting a cookie with a 7-day expiration
  • Reading the cookie value and displaying it
  • Removing the cookie completely

You can test this code to see how cookies work in practice, and modify the values and options as needed for your specific use case.


Best Practices and Considerations

When working with cookies in jQuery, consider these best practices:

Security Considerations

  • Always use the secure: true option for cookies containing sensitive data
  • Consider the SameSite attribute to prevent CSRF attacks (modern browsers support this)
  • Be careful with large cookie values as they have size limitations (typically 4KB per cookie)

Performance Considerations

  • Minimize the number of cookies you use
  • Keep cookie values as small as possible
  • Use appropriate expiration times to avoid accumulating stale cookies

Browser Compatibility

  • The jQuery cookie plugin works across all modern browsers
  • Test in different browsers to ensure consistent behavior
  • Consider server-side fallbacks for critical functionality

Alternative Libraries

While the jQuery cookie plugin is excellent, consider modern alternatives like js-cookie for more active maintenance and additional features:

javascript
// Using js-cookie library
Cookies.set('test', 1, { expires: 7 });
Cookies.get('test'); // Returns '1'
Cookies.remove('test');

As noted in the GitHub repository, the original jQuery cookie plugin is no longer maintained and has been superseded by js-cookie, though it remains functional for existing projects.

Remember: Cookies are stored on the client side and can be modified or deleted by users. Never store sensitive information in cookies without proper encryption and security measures.

Sources

  1. Stack Overflow - How do I set/unset a cookie with jQuery?
  2. SitePoint - jQuery Set Get Delete Cookies Example
  3. GeeksforGeeks - How to set and unset cookies using jQuery?
  4. Tutorial Republic - How to Set or Unset a Cookie with jQuery
  5. jQuery Cookie Plugin - GitHub
  6. Learning jQuery - Set/Get/Delete Cookies with jQuery
  7. SitePoint - Working with Cookies in jQuery
  8. JS Cookie - Modern JavaScript Cookie Library

Conclusion

Setting and unsetting cookies with jQuery is straightforward using the dedicated cookie plugin. For your specific example of creating a cookie named “test” with value “1”, simply use $.cookie("test", 1) to set it and $.removeCookie("test") to unset it. The plugin handles all the complexities of cookie manipulation while providing options for expiration, path, domain, and security settings.

Key takeaways:

  • Use $.cookie(name, value) to set basic cookies
  • Use $.removeCookie(name) to delete cookies
  • Add options like { expires: 7, path: "/" } for more control
  • Include both jQuery and the cookie plugin in your HTML
  • Consider security implications when working with cookies

For modern projects, consider exploring the js-cookie library as an alternative to the jQuery cookie plugin, though the jQuery approach remains perfectly functional for existing implementations. Always test cookie behavior across different browsers and be mindful of cookie size limitations and security best practices.