11 June, 2009


Chances are, at some point or other you'll have to work with cookies, the little pieces of data sent in HTTP requests.

Unfortunately, the way to work with cookies in JavaScript is absolutely horrible. Compounding the problem, there isn't any standard easy way to get/set a cookie, so we end up with dozens of different functions, each trying to do exactly the same thing.

Even worse, a lot of these functions (though they work), are very verbose and inefficient, making them both unwieldy and slow. If that wasn't bad enough, they often pollute the global namespace (sometimes with 3 global functions!).

As awful as dealing with cookies is, I found myself needing to do this. I had some criteria that I wanted in a cookie function:

  • Support getting/setting/deleting cookies.
  • Allow all the cookie settings, like path, domain, max-age, etc.
  • Use the same function for everything.
  • Lightweight in terms of code, and also very fast.
  • Use at most one global variable, preferably none.
  • Not tied to any libraries, making it easy to embed.
  • Simple and intuitive to use.

Nothing fulfilled all the above requirements, so I implemented my own. It uses the HTTP global variable, in case somebody wants to add another method dealing with HTTP.

You use it like this:

// Get a cookie:

// Set a cookie:
HTTP.cookie("test", "Hi!");

// Delete a cookie:
HTTP.cookie("test", null);

In addition, you can pass along a third parameter, which lets you set the special cookie settings:

// All the settings at once:
HTTP.cookie("test", "Hi!", {
    path: "/",
    domain: "temp",
    maxAge: 31536000,
    expires: new Date(2010, 0, 0),
    secure: true

Every setting works as you would expect. As per the specification, expires should be a GMT-string. You can pass in a string directly, or a Date object, which will then be converted into a GMT-string.

NOTE: If you set a cookie with path, domain, or secure, you must delete the cookie with the same settings. In other words: two cookies with the same name and value (but different settings) are considered as two different cookies.

[LINK] The source code.
[LINK] The unit tests.

[MDC] document.cookie

No comments:

Post a Comment