In my last couple of posts (‘C is for Cookie‘ and ‘Read Your Fortune…Cookie That Is‘), I spoke about cookies, how they are created and read, but what if you wish to get rid of a cookie? End users can clear out their cookies anytime they wish, but as developers, there might be times when we would like to clear a cookie. How can we accomplish this programmatically?
It is fairly simple…we just have to write a cookie with the name we would like to erase, have the value be blank and a date of -1. This will cause it to be erased. Here is some example code…
[code lang=”js”]
function eraseCookie(name) {
// Erase the specified cookie
// Function calls previous writeCookie function
writeCookie(name, "", -1);
}
[/code]
As you can see, I am utilizing the writeCookie() function that I blogged about already in ‘C is for Cookie‘. This is an example of where modality helps us in writing less code.
Now, a couple of questions to ask/keep in mind if we use cookies…
- Do cookies pose a security threat? Not if used properly. They are plain text. So, as a developer, it is your job to not make them insecure. Do not store sensitive data in them.
- What if we name a cookie the same as another application names theirs? Does not matter. Cookies are domain specific. So they will each be kept separate. It would only matter if you had two cookies with the same name within your web application.
- With cookies, do we even need a database? In most cases, yes. Cookies do not replace database functionality. End users can delete their cookies and we should not store sensitive data within them. Plus, by using a back end database, we can perhaps run data analytics/mining on our app data, but that is for another post.
- What about end users who have disabled cookies? While I believe this is probably rare, it is probably a good practice to test if they are enabled or not. Thankfully, browsers give us the ability to check this. We can run an if test on navigator.cookieEnabled. If this returns false, then cookies are disabled. We can then take whatever actions are appropriate.
Happy Coding!
Clay Hess