Even though, I've been a developer for over 25 years, I've never really dealt with cookies. Back in my Perl days, I used hidden fields to manage sessions. Now that I'm using express-session, I figured it would be a good idea to get more familiar with cookies. That turned out to be tougher than I thought it would be.
Normally, cookies are created by the server and, if the server enables the
HttpOnly flag, then your browser's JS code won't even be able to see the cookies. But, I like making demos that work in your browser.
It's very easy to add a cookie in your browser-
document.cookie = 'cookie1=New Cookie!'. And it's very easy to change it-
document.cookie = 'cookie1=New value.'. Deleting it is a different matter.
You don't actually delete cookies, you expire them. Most examples that I've found state that you should use some variation of
let date = new Date(0); document.cookie = 'cookie1=; expires='+date.toUTCString();
But I find that setting
max-age is easier-
document.cookie = 'cookie1=; max-age=0';
Something fun I learned is that you can have multiple cookies with the same name and different values.
document.cookie = 'cookie1=root; path=/'; document.cookie = 'cookie1=parent; path=/Parent'; document.cookie = 'cookie1=cwd;'; console.log(document.cookie);
If you serve the preceding code to a browser with the pathname
/Parent, then the output should be
cookie1=cwd; cookie1=parent; cookie1=root.
There are a few tricky points here. One, you can't use any arbitrary value for
path. It has to be an actual path in
document.location.pathname. Second, while
document.cookie will return all of the cookies, it won't tell you which one is associated with which path. The cookies are in ascending order from the longest to the shortest path. You can do something like
let cookies = document.cookie.split('; ') and the array will be in ascending order (tested on Chrome, Firefox, and Safari).
In order to alter or delete a specific cookie, you need to specify its corresponding path.
document.cookie = `cookie1=NewValue; path=/;`; document.cookie = `cookie1=; path=/; max-age=0;`;
You can't alter a cookie's path.
I should point out that running
document.cookie = 'cookie1=New Cookie!' is bad form. You should encode the data like so-
document.cookie = 'goodCookie=' +encodeURIComponent('data to encode'). This will allow you to use semicolons in your data.