cookie.jpg

HTTP Cookies - CRUD

Handling cookies in the browser, with JavaScript and the fundamental CRUD operations required.

3 minute read

What are HTTP Cookies?

Cookies are required for the persistence of data across pages and sessions, with the types Persistent Cookies and Session Cookies the period of time, or the parameters in which cookie data is retained can be controlled. Cookies are stored in an allocated space in the browser memory, as Key-Value-Pairs (KVP) and have flexible naming convention. Cookie data is transmitted to the server with an HTTP request in a Header field, the server can read and write cookie information in the response.

Cookies are used to store information about the page state, user information or analytical data. They can actually store anything, but there are some guidelines on usage and implementation: https://ico.org.uk/for-organisations/guide-to-pecr/cookies-and-similar-technologies/

CRUD Operations

Nothing new here:

  • Create
  • Read
  • Update
  • Delete

These are the foundations of systems interaction, particularly with data management. Database facades, WebApi driven applications, Content Management Systems and so on are all based on the ability to conduct the four operations.

 

Cookie Handling in JavaScript

Lots of libraries have methods to do this, including jQuery, but it’s actually very simple. Essentially there are 3 core methods; “Read, Write, Erase,” but an optional “Check” method makes things easier too.

Cookie Class

Include a Cookie class, basic KVP:

    var Cookie = function(name, value) {
        this.name = name;
        this.value = value;
    };

Read

    var read = function() {
        if (!document.cookie) {
            return false;
        }
        var cookies = [],
            ckeArr = document.cookie.split(/; */);
        for (var i = 0; i < ckeArr.length; i++) {
            var splitCookie = ckeArr[i].split('=');
            var ck = new Cookie(splitCookie[0], splitCookie[1]);
            cookies.push(ck);
        }
        return cookies;
    };

This method returns an array of Cookie (cookie class), which can then be used in client code.

Check

A bit like read (in fact it uses read), but retrieve a cookie by identifier:

     var check = function(name) {
        var ckes = read();
        for (var i in ckes) {
            if (ckes[i].name === name) {
                return ckes[i].value;
            }
        }
        return undefined;
    };

This will retrieve an individual cookie, if it exists.

Write

Of course we need to be able to write, as well as read:

     var write = function(name, value, exp) {
        if (exp != undefined) {
            var dateObj = new Date;
            dateObj.setDate(dateObj.getDate() + exp);
            dateObj.toUTCString();
        }
        document.cookie = exp !== undefined ? name + "=" + value + "; expires=" + dateObj + ';path=/' : name + "=" + value + ';path=/';
    };

Specify name, value and optional expiry date for the cookie and it will be written to the browser.

Erase

Using the write method, we can erase a cookie by nulling the expiry.

    var erase = function(name) {
        if (name !== undefined) {
            write(name, '', -1);
        } else {
            var ckes = this.read();
            for (var i in ckes) {
                write(ckes[i].name, '', -1);
            }
        }
    };

And those are the basic cookie handling operations! Combine all these methods together into an Object Literal or JavaScript class and you have a neat little module, which is light, for handling cookies in JavaScript.


  • Clientside
  • Novice
  • JavaScript
  • CRUD
  • Development

Leave a comment

Submit