Explain Codes LogoExplain Codes Logo

How do I set/unset a cookie with jQuery?

javascript
cookie-handling
jquery
javascript-api
Nikita BarsukovbyNikita Barsukov·Nov 28, 2024
TLDR

Set a cookie with the $.cookie command:

$.cookie('the_Cookie_Monster', 'yummy_cookie', { expires: 7, path: '/' });

Delete a cookie by setting its expiry to the past:

$.removeCookie('the_Cookie_Monster', { path: '/' });

Heads up: Above operations require the trusty jQuery Cookie plugin. On another note, amazing how we as developers can control the Cookie Monster better than Sesame Street ever could, huh?

First, before diving into the dark, delicious depths of cookie handling, it's important to swallow the basics of cookie handling. This includes creating, reading, and deleting cookies. Content that I promise will more satisfying than eating cookie dough. If you're a vanilla kind of developer, this section is just for you!

The beauty of the vanilla flavor

No jQuery? No biggies. JavaScript provides the deliciously sleek Document.cookie API for cookie manipulation:

Setting cookies without the calories of jQuery:

// Yup, that's how we "bake" a JavaScript cookie. Easier than your oven and no chance of burning your house down. document.cookie = "name=sugarRush; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";

Reading cookies like an open book:

const getCookie = (name) => { let cookieFile = document.cookie.split(";"); for(let recipe = 0; recipe < cookieFile.length; recipe++) { let cookieRecipe = cookieFile[recipe].split("="); if(name == cookieRecipe[0].trim()) { return decodeURIComponent(cookieRecipe[1]); } } return "That cookie does not exist, my friend."; };

Throwing cookies in the bin:

// This command sends our cookie to the Jurassic period, where it belongs. document.cookie = "name=sugarRush; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/;";

As the saying goes, keep your friends close and your cookies closer. 🍪

When dealing with sugar, salt, and cookies (or, you know, sensitive data), an extra hand never hurts. Enter js-cookie library. This little buddy takes away the hassle of cookie serialization and expands capabilities like a kitchen magician while you can sit back and munch on your cookies:

Cookies.set('cookie_name', 'cookie_value', { expires: 7 }); // Set a cookie, easy as pie (or, you know, cookie) console.log(Cookies.get('cookie_name')); // Read a cookie without moving a muscle! 🧐 Cookies.remove('cookie_name'); // Dump the cookie, adios mi amigo! 🗑️