Cookies

Cookie Monster

Unfortunately, not the kind you can eat (sorry, cookie monster). I was explaining how to manage cookies in JavaScript on a forum today and thought I would share.

Cookies are a good way to store temporary information about a user. The values will be stored in a file by the browser on the end-users computer, as long as they have them enabled. Fortunately, most people enable cookies, because they are needed by any site with a login. Since cookies are easy to read and stored on the end-users computer, one should never store any person or private infromation there. The cookies for a given domain are included in every request, so the back- and front-end both have access to them.

There are several limitations with cookies that should be considered before using them. The browsers manage the cookie IO, so each one slightly different, but all have a limit on the number of cookies for a domain, the maximum size of each cookie, and the maximum size of all cookies. To be conservative, a domain should have no more than 20 cookies, with a combined size less than 4kb. However, each server is configured with a maximum header size (this is where the cookies will be stored in each request), and 4kb will most likely exceed this limit. Plus, having large cookies will slow down your site, because it will be sent with each request. For this reason, it is more practicle to keep your cookie length under 100 characters.

I often use cookies to store the state of the site, such as with tabs or toggles so that when a user returns to the site their widgets are identical to their previous visits. In JavaScript cookies are stored in a String value at document.cookie, with each key/value pair separated by a semi-colon. Here are three functions to simplify interacting with cookies:

Example 1: Simple Cookie Functions

var createCookie = function(name, value, days) {
	var expires=null;
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	else {expires = "";}
	document.cookie = name+"="+value+expires+"; path=/";
};

var eraseCookie = function(name) {
	createCookie(name, , -1);
};

var readCookie = function(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;
};

However, if you are using the YUI framework, include their cookie package instead. It not only has all the features from Example 1, but it also supports sub-cookies, to defeat the 20 cookie limit.