Client Side Cookie Handling

There are many times that you'll need to handle cookies on the client (i.e. the web browser). Here's how you can use some simple JavaScript to provide all the cookie manipulation you'll ever need.

A Cookie Overview

You're probably pretty familiar with cookies, but in case you aren't, cookies are essentially pieces of data that are sent back and forth between your browser and a web server; usually in order to maintain session state. Originally implemented by Netscape, cookies were standardized by the Internet Engineering Task Force and adopted by all browsers.

Often you can use cookies to determine if a user is logged in or to reference a shopping cart id that the user is using. Although mostly cookies are used from a server-side programming perspective, there are times when its handy to be able to access cookie data from code running in the web browser itself via JavaScript.

Setting Cookies

So, how do we go about setting cookies? With JavaScript, you can access cookies via the document.cookie property. This property is a string that contains a number of attributes represented by name-value pairs that you separate by semicolons. For example, you can set this property to a string that says your cookie name "=" your cookie value. That's all there is to it. The one thing that you need to be careful of is escaping your cookie value(you can do this via the JavaScript 'escape' function). Cookies are passed back and forth between the browser and the server as HTTP headers, and you want to ensure that nothing in your cookie value gets garbled in the process.

But how do we handle cookie expiration? Simply by appending to the string a semicolon followed by "expires=" and the expiration time. If you don't specify an expiration time, by default your cookie is deleted when the user's browser is exited.

These are generally the three cookie properties you'll use most of the time-but they are not the only ones. We'll look at some other sections of the document.cookie string you can set in the next section.

Cookie Security

Three other attributes that you can set are 'domain', 'path', and 'secure'. Cookies can only be read by the server that set them. Cookies also have a path, which by default is the path of where they are set. This is important to know since when you try to retrieve a cookie you can only read it if you belong to the cookie path. Lastly, 'secure' indicates whether the cookie is intended for encrypted communication (such as SSL). This isn't a name-value pair, but simply the word 'secure' appended on to the document.cookie string.

We'll create a setCookie function that handles all of these parameters.

function setCookie(Name, Value)
var ArgumentCount;
var ArgumentValues;
var Domain;
var Expires;
var Path;
var Secure;

ArgumentValues = setCookie.arguments;
ArgumentCount = setCookie.arguments.length;

Expires = (ArgumentCount > 2) ? ArgumentValues[2] : null;
Path = (ArgumentCount > 3) ? ArgumentValues[3] : null;
Domain = (ArgumentCount > 4) ? ArgumentValues[4] : null;
Secure = (ArgumentCount > 5) ? ArgumentValues[5] : false;

document.cookie = Name + "=" + escape (Value) +
((Expires == null) ? "" : ("; expires=" + Expires.toGMTString())) +
((Path == null) ? "" : ("; path=" + Path)) +
((Domain == null) ? "" : ("; domain=" + Domain)) +
((Secure == true) ? "; secure" : "");

This function takes a minimum of two parameters, the Name and the Value of the cookie. This is the simplest of all cases. By using variable length arguments we can also handle the other parameters that we talked about above.

Retrieving Cookies

What we really need to do in order to retrieve a cookie value is to loop through the document.cookie string and look for the string cookie name "=". Once we've found this, we can pull the value out and return it. Code that does this is listed below:

function getCookie(Name)
var Argument;
var ArgumetLength;
var CookieLength;
var EndString;
var i;
var j;

Argument = Name + "=";
ArgumentLength = Argument.length;
CookieLength = document.cookie.length;
i = 0;
while (i < CookieLength)
j = i + ArgumentLength;
if (document.cookie.substring(i, j) == Argument)
EndString = document.cookie.indexOf (";", j);
if (EndString == -1)
EndString = document.cookie.length;
return unescape(document.cookie.substring(j, EndString));
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0)
return (null);

Deleting Cookies

Deleting cookies are easy. A straightforward way to do this would be to set the cookie's expiration time to before the current time; this should lead to your browser killing the cookie. The deleteCookie function uses both the getCookie and setCookie functions we listed above. See the code below.

function deleteCookie(Name)
var CookieValue;
var ExpirationDate;

ExpirationDate = new Date();
ExpirationDate.setTime (ExpirationDate.getTime() - 1);

/* Make Sure Cookie Exists First */
CookieValue = getCookie(Name);
if (CookieValue != null)
setCookie(Name, "", ExpirationDate, "/");


When using the above code, there are a few things you should be aware of. First, it is possible that a user can disable cookies in their web browser. Most modern browsers provide some kind of cookie management that allows them to turn off certain kinds of cookies or all cookies completely.

Secondly, most browsers will only allow you to set a maximum number of cookies and a maximum size of those cookies. Most browsers today allow you to set 50 cookies per domain, but you are likely to encounter browsers where this number is as low as 20. Also, Internet Explorer for example caps cookie content at 4K for all cookies from a specific domain.


Hopefully with the gotchas listed above in mind, the code in this article will handle most of your client-side cookie handling needs.

No comments :