Cookies

Create

Cookies have four parameters name, value, expiration, and path.

  • The name is a unique identifier for the cookie. The cookie name must be unique to the path it is set on.
  • A cookie only holds one value and it must be a string.
  • The expiration is the date and time after which the cookie becomes invalid.
  • The path should almost always be set to the root path=/ unless you have reason to set the cookie to a deeper path.
function setCookie(cName, cValue, cExDays)
{
    var d = new Date();
    d.setTime(d.getTime() + (cExDays*24*60*60*1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cName + "=" + cValue + "; " + expires + "; path=/";
}

// Set a cookie called "myCookie" with
// a value of "1" which will expire in 90 days.
setCookie( 'myCookie', 1, 90 );

Read

function getCookie( cName ) {
    var value = "; " + document.cookie;
    var parts = value.split("; " + cName + "=");
    if (parts.length == 2)
    {
        return parts.pop().split(";").shift();
    }
}

// Get the value of a cookie named "myCookie".
var myCookieValue = getCookie( 'myCookie' );

Update

To update a cookie, simply redefine it.

Delete

When a cookie expires it is automatically deleted, so to delete a cookie, set it’s expiration date to the past.

function delete_cookie( cookieName )
{
    document.cookie = cookieName +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
function delete_cookie( name, path, domain ) {
  if( get_cookie( name ) ) {
    document.cookie = name + "=" +
      ((path) ? ";path="+path:"")+
      ((domain)?";domain="+domain:"") +
      ";expires=Thu, 01 Jan 1970 00:00:01 GMT";
  }
}

Storing More Data

To store more complex data sets in a cookie you must first convert the javascript object into a string. After you retrieve the cookie value, you must then convert it back to a javascript object.

// Set a JS object.
var customerJsonObj = {
    'userName': 'Bob',
    'userId': '24735',
    'Likes': [{
        '0': 'Walking',
        '1': 'Trees'
    }],
    'totalPurchases': '6',
    'Dislikes': [{
        '0': 'Biking'
     }]
};

// Convert the jSon object into a string.
var customerJsonString = JSON.stringify(customerJsonObj);
 
// Set a cookie called 'customer', set the jSon
// string as its value and set a 90-day expiration.
setCookie('customer', customerJsonString, 90);

// Get the raw value of the cookie we just set.
var rawCustomerCookieValue = getCookie('customer');

// Parse the string into a jSon object.
var newCustomerJsonObj = JSON.parse(rawCustomerCookieValue);