Easy Javascript Cookies

Working with cookies in JavaScript can be a pain. Their is no clean api for working with them. It’s especially bad if you need to set multiple cookies. I ran into this issue recently when working with some custom search functionality on a WordPress site.

The page needed to use values from one page to do JavaScript based sorting on another page. I ended up using cookies and I had to set about 5 of them. So I created my own api for getting and setting cookies and i’m going to share it here.

The painful way

By default cookies are stored as a string on the window object. So to get or set cookies we can do the following.



// set a cookie
document.cookie = 'data=something;'
// get a cookie
var aCookie = document.cookie

 

You can also set the expiration date and a path on the cookie string. The default expiration date is just the next time the user closes there browser. Path is just what part of the site has access to the cookie. Setting path to ‘path=/’ makes the cookie avalable everywhere on that particular domain. By default the path is just the current page.

You can see how this gets hard to work with. Also if you want to set multiple cookies, you need to set document.cookie multiple times, like so.




document.cookie = 'data=something;path=/'
document.cookie = 'moreData=somethingElse;path=/'
document.cookie = 'evenMoreData=somethingElseAgain;path=/'

 

The worst part is retrieving the cookies. When you save the cookie string to a variable, as shown above. You get the whole cookie string. Now, if your building your own static page this isn’t really an issue; but most production sites are already using quite a few cookies. For example, heres the cookie string from Tech Crunch (A WordPress site, impressivly enough).



'__srret=1; _cb_ls=1; _chartbeat2=BU2euuDO81hOBC119y.1430261581106.1430261581120.1; __srui=c5db2f5d-e609-11e4-a818-22000a658da4; grvinsights=86f4863741cb67542455557b9cfd22a9; UNAUTHID=1.d41f3a22132c4f00a710de0a41ad214b.d99c; s_pers=%20s_fid%3D78BFB1ABC2779AB4-31BCFF423C481CF4%7C1495061120847%3B%20s_getnr%3D1431902720854-Repeat%7C1494974720854%3B%20s_nrgvo%3DRepeat%7C1494974720857%3B; s_sess=%20s_cc%3Dtrue%3B%20s_sq%3D%3B; __utmt=1; __utma=75736080.606718476.1430261581.1430261581.1431902721.2; __utmb=75736080.1.10.1431902721; __utmc=75736080; __utmz=75736080.1431902721.2.2.utmcsr=wpbeginner.com|utmccn=(referral)|utmcmd=referral|utmcct=/showcase/40-most-notable-big-name-brands-that-are-using-wordpress/; __nvu=fq6toq:50baa03d-7d1d-4695-b7eb-7c6d567fd8dc:e30=; __nvs=de88b593-8b8f-443d-b6a3-5bde94e795ee'

Yeah, have fun with that one. To get your cookie you would have to parse through all that. Sure you could write a function for that but there’s a better solution.

A Better Cookies API

Rather than dealing with cookies as a string, wouldn’t it be so much easier if we could manipulate them as a JavaScript object. Well we’re going to write a small library to make that happen. First well write a function to easily set multiple cookies.



// namespace our cookies library

;(function(window){

   window.cookies = {}

   // dont act like you don't want to name it this, ingredients will be our cookies object
   cookies.bake = function(ingredients){

        // set up initial variables
        var batch = ingredients || {},
            keys = [],
            values = [],
            size = 0,
            setString = ''
      
        // loop through the object saving its keys as an array
        for(var key in batch ){
            if (batch.hasOwnProperty(key)) {
                   var keyVals = key
                   keys.push(keyVals)
                   size++
            }
        }

        // do the same thing for its values 
        for(var prop in batch ){
            if (batch.hasOwnProperty(prop)) {
                   var propVals = batch[prop]
                   values.push(propVals)
            }
        }

        // now we loop through out two arrays and save them on the cookie string
        for (var i = 0; i <= size -1; i++) {

          document.cookie = keys[i] + '=' + values[i] + '; path=/'
        }     
    }

})(window)

Now we can set as many cookies as we need like this.



cookies.bake({
   'name' : 'someone',
   'occupation' : 'web developer',
   'location' : 'Cincinnati'
})

You’ll notice I left the expiration date set to default, and the path set as root. These are my most common use cases, but it would be pretty straight forward to pass the function an additional options object to set these yourself.

Retrieving the Cookies Object

We still need to add a function for retrieving our cookies as an object. This isn’t to hard since the cookies are already key value pairs and delimited by semicolons. Add the following inside of our anonymous function



cookies.get = function(){

      // define an object to store our cookies in
      var readyCookies = {}
      
      // convert the cookie string to an array
      var cooks = document.cookie.split(';')

      // loop through the array, split key value strings and add them to our object
      cooks.forEach(function(entry){
          var pairValues = entry.split('=')   
          readyCookies[pairValues[0].trim()] = pairValues[1].trim() 
      })
     
      // return the cookie string as an object
      return readyCookies
    }

Now on the page were we want to retrive the cookies, we just do



var cookieData = cookies.get()
// cookieData is now an object containing all the cookies
// we can access the cookies data like so
cookieData.name // equals someone
cookieData.occupation // equals web developer
cookieData.location // equals Cincinnati

And now we have a much improved cookies api, but we do need one more function to make it complete.

Deleting Cookies

You delete a cookie by setting its expiration date to a date that’s already past. So we’ll add one more function to do that.



// again don't act like you didn't want to 
cookies.eat = function(cookieName){
         document.cookie = cookieName + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/'
    }

This function takes the name of the cookie and deletes it. And there you have it, we have a simple to use , an adorably named api for working with cookies in JavaScript.

Awwwards