Although cookies almost seem like a prehistoric concept in web development, they’re a well understood commodity that still serve useful purposes. As such, I wanted to write up a quick column that demonstrates a common pattern involving cookies and JSON that you may find useful from time to time.

Dojo’s cookie module provides a consistent interface for getting and setting cookies. The simple dojo.cookie function handles the messy details of parsing the cookie string and is dual purposed: it acts as a getter if passed only one argument but acts as a setter if passed a second argument. In the case of acting as a setter, an additional third parameter allows you to pass in properties such as when the cookie expires, how to handle the cookie if a secure connection is not present, etc.

For example, you might set a key/value pair of foo=23 to expire after 5 days via a call to dojo.cookie("foo", "23", {expires : 5}). You could fetch back the value for foo via dojo.cookie("foo") but you’d have to also remember to use parseInt to cast it to a Number since cookies are returned as String values.

Well, managing lots of key/value pairs in this way gets cumbersome pretty quickly, so let’s use the dojo.toJson and dojo.fromJson functions to manage the serialization of more advanced data structures without much more effort. Thus, here’s that pattern I was referring to:


dojo.require("dojo.cookie"); //Pull down the dojo.cookie module

/* Serialize a complex data type... */
var foo = {bar : 0, baz : 23, quz : ['a','b','c']};
dojo.cookie("foo", dojo.toJson(foo)); //by default, the cookie will expire at the  end of the session

/* ...and then deserialize it when you need it back. */
foo = dojo.fromJson(dojo.cookie("foo")); //no further typecasting required

So, in other words, the next time you find yourself manipulating more than a few cookies, you may as well wrap them up into a hash and gain the benefits of JSON serialization, which provides the additional nicety of automatic typecasting.

My upcoming book, Dojo: The Definitive Guide includes coverage of simple patterns like these and a whole lot more. (See my last post for a table of contents preview.)