Helping ordinary people create extraordinary websites!

JavaScript Cookies

Cookies are small snippets of data stored on an internet client's computer that websites use to identify a user. Cookies can contain almost any data, but usually store small session IDs that allow the server to verify the end user has authenticated or otherwise uniquely identify the end user. Each domain name has a number of cookies stored together, which can be manipulated through JavaScript.

Creating JavaScript Cookies

document.cookie = "cookiename=cookievalue"

The document object stores all the cookies for a particular domain as a single string in its cookie property. Cookies are stored in name=value format. However, we should also add an "expires" setting to the cookie that sets when the cookie should expire. Typically one week is good for critical data (e.g. login tokens) and one month for general information (e.g. pages visited). To add an expires setting to a cookie, we add a semicolon, followed by "expires" and a GMT string of the expiry date. Thankfully, JavaScript provides the Date object to easily handle the complex datestamps:

var expires = new Date();
expires.setDate(expires.getDate() + 7); // 7 = days to expire
document.cookie = "logintoken=somelogintoken;expires=" + expires.toGMTString();

This first creates a new Date object, expires, and sets the date of expires to the current date plus 7 days. It then sets the cookie with this additional information, using the toGMTString() method on expires.

Accessing JavaScript Cookies

However, what if you want to create another cookie? Well, each time we create a new cookie, the browser adds it on to existing cookies, seperating them with a semicolon followed by a space. Consider this example:

document.cookie = "mycookie=val1";
document.cookie = "myothercookir=val2";
alert(document.cookie);

This will produce an alert box with the text "mycookie=val1; myothercookie=val2". Now, how do we access a particular cookie within this?

We can see that to access a cookie given its name, we would need to look for the cookie name followed by an equals sign. We do this using the indexOf method on the String object, that all string variables are an instance of, where indexOf searches for a particular string . indexOf takes one parameter, the string to search for, and optionally a second, where to start searching from (the offset) as a numeric position or index (e.g. 5 = five characters from the start). Most cookies will end with a semicolon, so we look for that. The ones that don't are the last in document.cookie, so we presume the end is the end of document.cookie, which is conveniently available in the length property. We then use the similar substring method to extract the section from the start to the end. Here's the code:

start = document.cookie.indexOf("mycookiename=");
end = document.cookie.indexOf(";", start); // First ; after start
if (end == -1) end = document.cookie.length; // failed indexOf = -1
cookie = document.cookie.substring(start, end);

It's all fairly simple once you understand a string. Consider the string "thishasnospaces". To JavaScript, this can be represented as the following:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
t h i s h a s n o s p a c e s

If we stored this in a string and ran indexOf("has"), we would get 4, because that is where the "has" section starts. If we ran substring(4, 6), we would get "has", because that extracts from 4 to 6. If you store the entire string in a variable, e.g. somestring, you can access it just like an array element with somestring[index], e.g. somestring[4] = "h". This is called the string index.

Safe JavaScript Cookies

Storing raw cookie data is all very well, but what if we want to put in an equals sign into our cookie value? How does the browse handle a cookie like mycookie=my=value; ? Quite simply, it doesn't. You are responsible for preventing this. Luckily, it's very easy, through a method known as URL encoding. Through URL encoding, most special characters have an alternate value that starts with a % percentage symbol and is followed by the character code. For example, a space is %20, which you might have seen in URLs before. See Wikipedia for more information on URL encoding.

All we have to do to take advantage of URL encoding is pass our value through the escape() function. This will take any special characters and convert them to URL-encoded equivalents. For example, to set a cookie, we should really use document.cookie="mycookiename"+escape("mycookievalue"). While this isn't as important when we set the exact value of a cookie, you should always use it when you set the value through a variable, e.g. escape(somevariable).

Bringing it all together

Setting and retrieving cookies is very straightforward, and you will often find yourself copying and pasting similar code. To help you, we've created two simple JavaScript functions to set and get cookies. Feel free to copy this code into your JavaScript and use it whenever you wish.

function DT_setcookie(name, value, expirydays = 7) {
expiry = new Date();
expiry.setDate(expiry.getDate() + expirydays);
document.cookie = name+"="+escape(value)+";expires="+expiry.toGMTString();
return document.cookie;
}
function DT_getcookie(name) {
start = document.cookie.indexOf(name+"=");
end = document.cookie.indexOf(";", start); // First ; after start
if (end == -1) end = document.cookie.length; // failed indexOf = -1
return document.cookie.substring(start, end);
}

These two functions include every JavaScript cookie-related issue we've covered on this page.

« JavaScript Redirect JavaScript Events »


More JavaScript Tutorials:
» How to Setup a Randomising Function
» Ensuring Two Form Fields Have Identical Information
» Javascript Diff Algorithm
» Using Arrays in JavaScripts
» Form Submissions Without Submit Buttons
» Submit Forms Conditionally using JavaScript
SPREAD THE WORD!
Tell a Friend

GET OUR NEWS

Developer Resources