JavaScript Cookies: Yummy

Most of the time cookies are handled by the server using languages like PHP or Ruby, but there are times when using JavaScript to handle the cookies is the best option. Cookies are a strange beast in JavaScript and many developers don’t know how to use them. That’s all about to change!

Short Introduction to Cookies

You probably know what cookies are, but there is a definite possibility that someone out there doesn’t know. Essentially a cookie is a small key/value pair of data that is stored on the user’s computer. That data is sent back and forth between the browser and the server so that the server can recognize the user between requests and keep track of important information about the user that the server/front end JavaScript can respond to. This is the most common way of keeping people logged in.

Along with the key and the value, cookies also contain expiration, path, and domain data. The expiration sets when the cookie ceases to exist and is a date using a GMT formatted string. The path can be set to only allow a cookie to work in certain parts of a website. For example, if your website was example.com and you set the path to “/path”, then the cookie would only be used when the user is on a page that starts with “example.com/path”. The domain attribute can be used by subdomains so that data is available across all of the subdomains. For example, if you were on member.example.com and you set a cookie normally, then the cookie would only be available on member.example.com, but you could set the domain to “example.com” and then the cookie would be available on the top level domain and all of its subdomains.

It is important to note that you can only set cookies to be within your own domain and you can’t pull information from cookies set on other domains.

For the most part, you’ll probably just be using a jQuery plugin or standalone library to help you mess around with cookies. For this, I recommend this JavaScript Cookie Handling Library on Google Code. It comes as both a jQuery plugin and a standalone library. It is lightweight (I don’t see how a cookie library wouldn’t be) and contains some rarely used, but very powerful features. It even has a way to link the data of an input field to a cookie so that whenever the input field’s value changes, the cookie automatically does too.

Keeping Cookies in Your Own Jar

I won’t bother telling you how to use that plugin because it has some very nice documentation and it’s quite straightforward. I was planning on actually telling you how to use cookies without a library, just in case you’re one of those people who likes to write their own plugins or you prefer to work without the aid of third party libraries.

Cookies

We’ll start out by learning how to set a cookie.

1
document.cookie = "key=value";

Wow, that was simple! There are a few things to make note of though. 1) The cookies are stored in document.cookie. 2) The format for a cookie is “key=value” without any spaces. 3)You add a cookie just by assigning document.cookie to the new cookie. That cookie property is not a normal property; assigning the new cookie to it does not override any of the previously set cookies.

If you’d like to set the extra options – such as expires or path – to the cookie, then here’s how you’d do that.

1
2
3
4
5
6
7
8
9
10
var key =   "key",
value = "value",
// Set the date to the end of time ;P
exp = new Date("December 21, 2012"),
dom = "example.com"
path = "/path";

exp = exp.toGMTString();

document.cookie = key+ "=" +value+ ";expires=" +exp+ ";domain=" +dom+ ";path=" +path;

Just separate all of the meta data with a semicolon and keep using the “key=value” format. Now, setting a cookie might not be all that useful if you can’t retrieve it later. You can actually get all of the data directly from document.cookie because it holds a string. There is one thing that might be good to know that confused me for a while: if you are retrieving cookies from document.cookie, the meta data doesn’t actually show up there. This is good because we don’t need to filter out the meta data.

Below is a function that can be used to retrieve a cookie.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function getCookie(name) {
var name = name + "=",
cookie = "",
cookies = document.cookie.split(';'),
len = cookies.length, i=0;

for(;i < len; i++) {
cookie = cookies[i];

while (cookie.charAt(0)==' ')
cookie = cookie.substring(1,cookie.length);

if (cookie.indexOf(name) == 0)
return cookie.substring(name.length, cookie.length);
}
return null;
}

After that, all you need to know how to do is to delete a cookie, which is dead simple. All you have to do is set a cookie with the same key as the cookie you’re trying to remove and set the date to a time in the past so it will immediately expire. You could even just assign it to the current time so it’ll expire one millisecond later.

That wraps up our little talk on those tasty cookies (seriously, why are they called that?) in JavaScript. Stay tuned for another tasty post on Thursday where we’ll be talking about a single character that does some very strange things in JavaScript. I’ll give you a hint: it’s on your keyboard somewhere… at least I assume so; I don’t really know what keyboards look like in Asia.

If you happen to know the reason why they’re called cookies, or you just feel like leaving a friendly “hello”, please feel free to add a comment. Also, I’m sure there are a few JavaScript programmers in the world who don’t know about this blog and might like to read this post, so give them a chance by sharing this post using the buttons below. Happy Coding!

Author: Joe Zimmerman

Author: Joe Zimmerman Joe Zimmerman has been doing web development ever since he found an HTML book on his dad's shelf when he was 12. Since then, JavaScript has grown in popularity and he has become passionate about it. He also loves to teach others though his blog and other popular blogs. When he's not writing code, he's spending time with his wife and children and leading them in God's Word.