Skip to main content

How to Set a Cookie with JavaScript

Learn how to set a cookie with JavaScript and how to use and delete it.

Overview

A cookie is a string that you can store in the browsers of people who visit your web site. You can put whatever information you want into a cookie, so that when a visitor returns to your site, you can retrieve the cookie and make use of the information that you saved in it.

Below is an example of the JavaScript required to create a simple cookie.

document.cookie="yourname=" + prompt("What is your name?");

The simple example above will ask you for your name, and then will set a cookie that includes your name in it.

You can retrieve the cookies for any given web page via the document.cookie object. Here is a custom function that will return the yourname part of the cookie.

function getCookieValue(key)
{
    currentcookie = document.cookie;
    if (currentcookie.length > 0)
    {
        firstidx = currentcookie.indexOf(key + "=");
        if (firstidx != -1)
        {
            firstidx = firstidx + key.length + 1;
            lastidx = currentcookie.indexOf(";",firstidx);
            if (lastidx == -1)
            {
                lastidx = currentcookie.length;
            }
            return unescape(currentcookie.substring(firstidx, lastidx));
        }
    }
    return "";
}

alert(getCookieValue("yourname"));



The cookie that has your name in it, from the example above, will be deleted from your browser as soon as you close it. If you want to make the most of cookies, you want to be able to make your cookie last longer than that.

If you create a variable using new Date(), the variable will have the current time in it, based on the system clock of the person visiting the web page. The variable will not update that value, though, so if you let the variable sit around for ten minutes, its value will then be ten minutes in the past.

In order to set the expiration date of a cookie, you have to give it an expiration date in GMT format. You can include the expiration date as part of the string that you assign to document.cookie. For example:

document.cookie = "examplecookie=examplevalue;"
                + "expires=Sat, 16 May 2009 18:40:22 GMT";

The Date object has some helpful functions that make it fairly easy to create a GMT string of whatever date you want. If you try to just add numbers to your Date variable, however, you might not get the results that you expect. Creating a Date object that stores a future date is a little more complicated than that.

Using the getTime() function on a Date object returns the number of milliseconds that have passed since midnight on January 1, 1970, up to the time stored in that Date object. It's a little weird, but in order to have useful date functions, it is important for the Date object to have a starting point. The setTime() function takes a number of milliseconds as the argument, and generates a date that is that many milliseconds after midnight on January 1, 1970.

In the example below, I create a new Date object in a variable. Then I get its millisecond offset with getTime(), add one second (1000 milliseconds) to that time. I use that value to create a new Date object. At the end, I use the toGMTString() function to output the date variables as GMT strings.

var currtime = new Date();

var newtime = new Date(currtime.getTime() + 1000);

alert(currtime.toGMTString() + "\n" + newtime.toGMTString());

Helpful Time Functions

If you want to use the Date object to create an expiration date for a cookie, you will want to be able to add more than just a second to the current time. The numbers get a little confusing, so here are some helpful functions that allow you to pass a number of seconds, minutes, hours, days, and years (respectively) as an argument, and get that number back in milliseconds.

function secondsInMilliseconds(numseconds)
{
   return numseconds * 1000;
}

function minutesInMilliseconds(numminutes)
{
  return secondsInMilliseconds(numminutes * 60);
}

function hoursInMilliseconds(numhours)
{
  return minutesInMilliseconds(numhours * 60);
}

function daysInMilliseconds(numdays)
{
  return hoursInMilliseconds(numdays * 24);
}

function yearsInMilliseconds(numyears)
{
  return daysInMilliseconds(numyears * 365);
}

Using these functions, we can set a cookie to expire some time in the future. Let's create a cookie that will expire in 10 days.

var expiremilliseconds = daysInMilliseconds(10);

var currdate = new Date();

var expirationdate = new Date(currdate.getTime() + expiremilliseconds);

document.cookie="tendays="
               + prompt("What is your favorite color?")
               + ";expires=" + expirationdate.toGMTString();

alert("The cookie value is "
       + getCookieValue("tendays")
       + ". It will expire on "
      + expirationdate.toGMTString());

If you come back to this page later (assuming you haven't deleted your cookies), the cookie should have the same value as the one you just set, unless 10 days have passed. After 10 days, the cookie will automatically get deleted from your browser.

You can set cookies to expire a really long time from now, but there are some limits to it. Currently, some computers will not accept a cookie expiration date in 2038 or later.

You can restrict a cookie to only work if the visitor is in a certain subdirectory. If your JavaScript tries to access the restricted cookie from a different subdirectory, you won't find it.

You can make a cookie available to all the directories in your domain name like so:

document.cookie = "examplekey=examplevalue;path=/";

The cookie above will be available to all web pages on the site where the cookie was set.

Or you can restrict the cookie to a specific directory like so:

document.cookie = "examplekey=examplevalue;path=/exampledirectory";

The cookie above will be available to all web pages in the /exampledirectory/ directory, as well as to any pages in subdirectories of /exampledirectory/.

For security reasons, a web page is only allowed to set a cookie on its own domain. It cannot set cookies on other people's web sites.

However, you can change the subdomain of the current web site that your cookie is available to. If you use subdomains (for example, subdomain.example.com), you might want to set a cookie that is valid only for that subdomain. Here is how to do that:

document.cookie = "examplekey=examplevalue;domain=subdomain.example.com";

Similarly, if you want to make sure that your cookie is available to all subdomains of your site, you can do the following.

document.cookie = "examplekey=examplevalue;domain=.example.com";

When using the domain property in a cookie, the value that you set for it must include at least two periods.

There is one more option to mention: secure. It doesn't take any values; you just add secure after a semicolon in your cookie string. Including secure in a cookie makes that cookie only be available to an SSL server, for example https://www.example.com/

Here is how to use it:

document.cookie = "examplekey=examplevalue;secure";

Get help with games!