Create and use cookies with JavaScript…

So in this we are going to go over a simple Vanilla JS way to create and use cookies. There are a lot of plugins, libraries, and other ways to do this, but if you need an on-the-fly way to do this and do not want to depend on loading up extra libraries this will serve your needs nicely. I personally use this for creating cookies and utilizing them in different ways on numerous websites. Remember not to store sensitive information unencrypted in cookies ever. It is a very bad practice to get into and has some very negative consequences for site security.

The Javascript to do this can be modified and altered to suit your needs. You can create session cookies with this or persistent cookies which will be saved for a period of time of your choosing. I use this both for session and persistent cookies based on my needs. So let’s take a look at some of the code…

JavaScript to create and read cookies

function createCookie(name,value,days) { // this function will actually take an input of name / value / days and create a client-side cookie
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}

function readCookie(name) { // this function will parse through client-side cookies and read out values based on cookie names input
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
};

This code is a bit much to really go in depth and explain what everything is doing, but I will give some brief details about it. Starting off, we are creating two named functions, one is createCookie and the other is readCookie. These two functions together will allow us to create new cookies, edit existing cookies, and read cookies. When creating or editing cookies we can update or change the expiration if we want as well.

So with this code loaded in, if we wanted to create a new cookie, and then get its values we would do something like this...

Actually creating a cookie with above functions in JavaScript

createCookie('test-cookie-name','test-value', 7); // creates a cookie named test-cookie-name with a value of test-value which will expire in 7 days

readCookie('test-cookie-name'); // will output test-value

Ok, so great, we have now used some JavaScript functions and some simple JavaScript to actually create and store a cookie client-side. While this does not seem too impressive because it is a test cookie with a test value, this can become much more powerful when you think about what you can do with this even storing harmless bits of information. For instance, on an e-commerce site you could store products a user visits more than once, you could store custom values or preferences for a user, even in a single session you could store useful information if a user was filling out a questionnaire and you wanted to perhaps show custom content based on the user's choices, the list goes on...

Some additional code examples

function createCookie(name,value,days) { // this function will actually take an input of name / value / days and create a client-side cookie
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/; secure"; // adding the secure on the end will force your cookies to only send over HTTPS if you have a valid SSL cert enabled, it is a good idea to do this if you have https enabled and working properly
}

function createCookie(name,value) { // this function will actually taken input of name / value and create a client-side cookie
    document.cookie = name + "=" + (value || "") + "; path=/"; // this will store a cookie as session based since there is no expiration, still not safe to store sensitive information, even if you also are sending it over HTTPS
}

Securing Cookies

September 20, 2018