JS Cookies

Welcome to another tutorial, here you will learn to create, read, update and delete a cookie in JavaScript.
 

What is a Cookie

A cookie can be defined as a small text file that lets you store a small amount of data (of nearly 4KB) on the user's computer. Cookies are mainly used in keeping track of information such as user preferences that the site can retrieve to personalize the page when a user visits the website next time.

The cookies are an old client-side storage mechanism. It was originally designed for use by server-side scripting languages such as PHP, ASP, etc. But, they can also be created, accessed, and modified directly using JavaScript, however, the process is a little bit complicated and messy.

Tip: Cookies can take up to 4 KB of space in the user's computer, including their name and values, cookies that exceed this length are trimmed to fit. therefore, each time the browser requests a page to the server, all the data in the cookie is automatically sent to the server within that request.

Warning: Beware of sensitive data such as a password or credit card information in cookies since it could potentially be manipulated by the malicious user so don’t store them.
 

Creating a Cookie in JavaScript

Cookies can be created, read, and deleted with the document.cookie property in JavaScript. All cookies associated with a document are represented by this property.

To create or store a new cookie, You can assign a name=value string to this property, to create or store a new cookie. This is shown below:

document.cookie = "firstName=Alex";

The values of cookies cannot contain commas, semicolons, or spaces. Therefore, you will need to use JavaScript's built-in function encodeURIComponent() to encode the values containing these characters before you can store them in the cookie. similarly, you will need to use the corresponding decodeURIComponent() function when you read the cookie value.

document.cookie = "name=" + encodeURIComponent("Nikolos Columbus");

By default, the current browser session is the lifetime of a cookie. This means it is lost when the user exits the browser. But, for a cookie to exist beyond the current browser session, its lifetime needs to be specified (in seconds) with a max-age attribute. This max-age attribute determines how long a cookie can exist on the user's system before it is deleted. For instance, the following cookie will live for 30 days.

document.cookie = "firstName=Christopher; max-age=" + 30*24*60*60;

The lifetime of a cookie can be specified with the expires attribute. This attribute makes use of an exact date (in GMT/UTC format) when the cookie should expire, instead of an offset in seconds.

document.cookie = "firstName=Christopher; expires=Thu, 31 Dec 2099 23:59:59 GMT";

Below is a function that sets a cookie with an optional max-age attribute. However, You can use the same function to delete a cookie by passing the value 0 for daysToLive parameter.

function setCookie(name, value, daysToLive) {
    // Encode value in order to escape semicolons, commas, and whitespace
    var cookie = name + "=" + encodeURIComponent(value);
    
    if(typeof daysToLive === "number") {
        /* Sets the max-age attribute so that the cookie expires
        after the specified number of days */
        cookie += "; max-age=" + (daysToLive*24*60*60);
        
        document.cookie = cookie;
    }
}

By default, a cookie is available to all web pages of a website in the same directory (or any subdirectories of that directory). But, when you specify a path, the cookie is available to all web pages in that specified path and all web pages in all subdirectories of the same path. For instance, if the path is set to / the cookie is available throughout a website, without which page creates the cookie.

document.cookie = "firstName=Christopher; path=/";

In addition, the domain attribute can be used if you want a cookie to be available across subdomains. By default, cookies are available only to the pages in the domain they were set in in a website/browser.

Note: if a cookie created by a page on ‘blog.example.com’ sets its path attribute to / and its domain attribute to ‘example.com’, the cookie is also available to all web pages on ‘backend.example.com’, and ‘portal.example.com’. But, you cannot share cookies outside its domain.

document.cookie = "firstName=Christopher; path=/; domain=example.com";

A boolean attribute named secure is also available. For instance, if this attribute is specified, the cookie will only be transmitted over a secure (i.e encrypted) connection such as HTTPS.

document.cookie = "firstName=Christopher; path=/; domain=example.com; secure";

 

Reading a Cookie

Reading a cookie is slightly more complex as a result of the document.cookie property returns a string containing a semicolon and a space-separated list of all cookies (i.e name=value pairs), for instance, firstName=John; lastName=Doe. However, this string doesn't contain the attributes such as expires, path, domain, etc., that might have been set for the cookie.

For you to get the individual cookie from this list, you need to make use of the split() method and break it into individual name=value pairs, and search for the specific name, as shown in the example below:

function getCookie(name) {
    // Split cookie string and get all individual name=value pairs in an array
    var cookieArr = document.cookie.split(";");
    
    // Loop through the array elements
    for(var i = 0; i < cookieArr.length; i++) {
        var cookiePair = cookieArr[i].split("=");
        
        /* Removing whitespace at the beginning of the cookie name
        and compare it with the given string */
        if(name == cookiePair[0].trim()) {
            // Decode the cookie value and return
            return decodeURIComponent(cookiePair[1]);
        }
    }
    
    // Return null if not found
    return null;
}

Let’s create one more function ‘checkCookie()’ that will check whether the firstName cookie is set or not, by utilizing the above getCookie() function. If the cookie is set then this function will display a greeting message, and if it is not then this function will prompt the user to enter their first name and store it in the cookie using our previously created setCookie() function.

function checkCookie() {
    // Get cookie using our custom function
    var firstName = getCookie("firstName");
    
    if(firstName != "") {
        alert("Welcome again, " + firstName);
    } else {
        firstName = prompt("Please enter your first name:");
        if(firstName != "" && firstName != null) {
            // Set cookie using our custom function
            setCookie("firstName", firstName, 30);
        }
    }
}

 

Updating a Cookie

The available way to update or modify a cookie is by creating another cookie with the same name and path as an existing one. Creating a cookie with the same name but a different path, then the existing one will add an additional cookie. 

Below is an example:

// Creating a cookie
document.cookie = "firstName=Christopher; path=/; max-age=" + 30*24*60*60;

// Updating the cookie
document.cookie = "firstName=Alexander; path=/; max-age=" + 365*24*60*60;


Deleting a Cookie

To delete a cookie, just set it once again by ensuring you use the same name, then specifying an empty or arbitrary value, and set its max-age attribute to 0. Do not forget, if you've specified a path, and domain attribute for the cookie, you'll also need to include them when deleting it.

// Deleting a cookie
document.cookie = "firstName=; max-age=0";

// Specifying path and domain while deleting cookie
document.cookie = "firstName=; path=/; domain=example.com; max-age=0";

But, to delete a cookie using the expires attribute, do it by setting its value (i.e the expiration date) to a date that has already passed, as demonstrated in the example below.

document.cookie = "firstName=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";