Javascript Cookies

Cookies are a great way to store bits of information about the visitors to your site. You can store things like the users prefered layout or their selections on a shopping site. This page provides functions to get an existing cookie, remove an existing cookie or create a new cookie.

Creating a Cookie

Before you can retrieve or delete a cookie you first need to create one. Below you'll see the code I use to set a cookie.

function setCookie(name, value, days) { if (typeof days == 'undefined') days = 28; var expiry = new Date(new Date().getTime() + days * 86400000).toGMTString(); document.cookie=name + "=" + escape(value) + "; expires=" + expiry; }

The setCookie function takes 3 parameters. The name used to reference the cookie, the value to be stored in the cookie and the number of days to keep the cookie for. The days parameter is optional and the cookie will be stored for 28 days if it is omitted.

The setCookie function might be used like this.

setCookie("testCookie", "Test Cookie Value");

If you call the setCookie function with the same cookie name as a cookie that already exists you will overwrite the existing cookie with the new cookie value. We make use of this behaviour later when deleting cookies.

Retrieving a Cookie

Now that we've got a cookie we need a way to get the value stored in it. I use the getCookie function shown below.

function getCookie(name) { var re = new RegExp(name + "=([^;]+)"); var value = re.exec(document.cookie); return (value != null) ? unescape(value[1]) : null; }

This function takes just one parameter, the name of the cookie to be retrieved. The getCookie function will return the string value stored in the cookie or null if the cookie does not exist.

You could display the value stored in a cookie with this code.

alert(getCookie("testCookie"));

Delete a Cookie

To delete a cookie all we need to do is overwrite the existing cookie with one that has already expired. We could use the setCookie method to do this as shown.

setCookie("testCookie", "", -1);

This works by overwriting the existing cookie with one that expired a day ago. This is pretty simple but to keep things clean I tend to use the helper function shown below.

function deleteCookie(name) { setCookie(name, "", -1); }

This function does essentially the same thing as using setCookie with a negative day value, but I think the resulting code is easier to follow.

Example

Here's an example of the cookie functions in action. Use the buttons below to set, retrieve and delete cookies.

Set a Cookie

Cookie Name :
Cookie Value :
Cookie Duration (days) :

Get a Cookie

Cookie Name :

Delete a Cookie

Cookie Name :