How to Use Cookies in JavaScript - dummies

By John Paul Mueller

Cookies store application information on the user’s drive. When a user visits a site, the JavaScript application can use a cookie to store information for future use. Some cookies are quite simple and store the user’s name or the date of the user’s last visit. Other cookies are quite complex and could store information about application state.

A cookie could put a user back to where the user was the last time the application was active. No matter how simple or complex a cookie is, the basic techniques for working with cookies are the same.

How to set a cookie with JavaScript

It pays to create functions that will set and get cookies so that you don’t have to write the same code repeatedly. The following example accepts three inputs: the name of the cookie, the value of the cookie, and the number of days until it expires:

function SetCookie(Name, Value, Expiration)
  // Create a date variable that contains
  // the expiration date.
  var ExpDate = new Date();
  if (Expiration != null)
   ExpDate.setDate(ExpDate.getDate() +
  // Encode the data for storage.
  var CookieValue = escape(Value) +
   "; expires=" + ExpDate.toUTCString();
  // Store the cookie.
  document.cookie = Name + "=" + CookieValue;

Normally, you’d add data input checks to a function that you plan to use in a variety of situations. This example leaves them out for the sake of clarity.

The code begins by calculating the expiration date. It begins by creating a new Date object, ExpDate, and adding the number of days until the cookie expires to it. Always think of the expiration date as more of a suggestion than an absolute. A user can configure the browser to remove cookies each time the browser is shut down, or the user can remove the cookies manually at any time.

To store a cookie value, you must escape it — that is, remove any whitespace characters from it. The example removes the space characters and then adds the expiration date. Suppose you want to store a cookie, Username, with a value of John.

What you end up with is a string that contains the username and expiration date: John; expires=Sun, 08 Dec 2013 21:43:52 GMT. The cookie’s actually stored in the document.cookie property as Username=John; expires=Sun, 08 Dec 2013 21:43:52 GMT.

How to get a cookie

Assuming the user has saved the cookies your application created, you need to retrieve them before you can make use of the data they contain. The values are stored on disk as name/value pairs. The data is escaped, which makes it easy to store but impossible to read. The following code shows how to retrieve all the cookies, search for a specific cookie, and then make the data readable:

function GetCookie(Name)
  // Obtain all of the cookies and split
  // them into individual cookies.
  var Cookies=document.cookie.split(";");
  // Process each cookie in turn.
  for (var i=0; i<Cookies.length; i++)
   // Obtain the name of the cookie.
   var CName = Cookies[i].substr(0,
   // Obtain the value of the cookie.
   var CValue = Cookies[i].substr(
     Cookies[i].indexOf("=") + 1);
   // Replace any escaped characters.
   CName = CName.replace(/^s+|s+$/g, ");
   // If the name of the cookie matches the
   // name that was passed by the caller, return
   // the associated cookie.
   if (Name == CName)
     return unescape(CValue);
  // Return a null value when the cookie isn't found.
  return null;

The cookies are stored as one long string where each cookie is separated from the next by a semicolon (;). The example uses the split() function to turn this string into an array of individual cookies. At this point, the code can process the cookies one at a time.

Each cookie is stored as a name/value pair. The code begins by retrieving the name, and then the value, using string manipulation functions. Another way to perform the same task is to use the split() function again with equals (=) as the delimiter. You would then find the name in the first array element and the value in the second array element.

You now have an escaped name and value. The code removes the escape characters in the cookie name so that it can perform a direct comparison with the name that was passed to the function. When the names match, the code returns the value to the caller.

How to check a cookie with JavaScript

The GetCookie() and SetCookie() functions make it easy to work with cookies by using JavaScript. This example tracks the user’s name. When the system doesn’t have the user’s name stored, the application asks for it and stores it for later use as shown in the following example:

function CheckName()
  // Obtain the user's name.
  var UserName = GetCookie("Username");
  // Check for a user name.
  if ((UserName == null) || (UserName == "))
   // Obtain a username from the user.
   UserName = prompt("Please type your name: ");
   // Set a cookie for the username that will
   // expire in one year.
   SetCookie("Username", UserName, 365);
   // Otherwise, extend the message.
   UserName = "Back " + UserName;
  // Display the user's name onscreen.
  var SetName = document.getElementById("Name");
  SetName.innerHTML = UserName;

The function begins by attempting to get the stored cookie. When there’s no cookie to get, the function returns null. A user could also choose to simply press Enter when asked for a name. This would result in a blank value. The code also checks for a blank and asks the user to enter a name again.

When there’s a name stored on the drive, the code modifies the message onscreen to reflect this fact. So, if this is a new user, the message says Welcome Name, but if this is a returning user, it says Welcome Back Name. The point is that you have a simple method for detecting returns versus new entries.