Understanding and working with Cookies


Reading time: 35 minutes

Cookies are the most commonly used technique by which websites store information on a user's browser. This has its own advantages such as personalized browsing, more relevant content and others along with some disadvantages such as activity tracking. In this article, you will understand:

  • The basic idea of cookies
  • Different types of cookies like third party and persistent
  • How to set, get and delete cookies in JavaScript?
  • How to view cookies? and how the World looks at it?
  • A demo to understand the inner workings of cookies

What are Cookies?

A cookie is a small amount of text information given by the web server to web browser. This helps the server differentiate a first-time user from a regular user.
This data is stored on the visitor's hard drive, and is retrieved each time the browser visits the specific website. A cookie can only be retrieved and read by the domain that has placed it on the visitor's machine.

According to the definition provided by Microsoft:

A Cookie is a small text based file given to a user by a visited website that helps identify the user to that site. Cookies are used to maintain state information as the user navigates different pages on a Web site or return to the Web site at a later time.

Web browsing is personalised by the use of cookies, and they may also enable quicker access to some websites.

Temporary vs Persistent Cookies

A temporary cookie is one which is removed from the visitor's local hard drive as soon as the browser is closed or the session expires. These are also called session cookies.

Persistent cookies are stored in the visitor's hard drive, even after the browser is closed. This helps in uniquely identifying the web browser on subsequent visits.

First-Party vs Third-Party Cookies

Cookies that originate from the host domain are first-party cookies.These usually store the preferences of the visitor while visiting the website.
Cookies that originate from any other domain are third-party cookies. If there are ads on a website served by a third-party, cookies are served alongside, and saved to the visitors machine. These are usually used for advertising or marketing purposes.

How to Set Cookies?

Cookies come in name-value pairs, like: name=John.
To set a cookie in JavaScript:

document.cookie = "cookiename=cookievalue"

You can add an expiry date so that the particular cookie will be deleted on that date:

document.cookie = "cookiename=cookievalue;expires=Sun, 21 Jul 2019 14:00:00 IST"

Function to create a cookie:

function createCookie() 
{
    var d = new Date();
    d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000));
    document.cookie = document.getElementById("name").value + "=" + document.getElementById("value").value + ",expires=" + d.toUTCString() + ",path=/;";
    alert(document.cookie);
}

How to Get Cookies?

One can get cookies using the cookie property of document as follows:

var x = document.cookie

How to Delete Cookies?

To delete a cookie, just set the values of the cookie empty, and set the expiry date to a date which has passed:

document.cookie = "cookiename=;expires=Mon, 01 Jul 2019 14:00:00 IST"

Function to delete a cookie:

function deleteCookie() 
{
    var name = document.getElementById("delete").value;
    var cookie = getCookie(name);
    var d = new Date('January 01, 2001 00:00:01');
    document.cookie = name + "=,expires=" + d.toUTCString() + ",path=/;";
}

Cookie String

Cookies are text strings. However, if you create a new cookie, the old cookie is not overwritten, but added to the old string:

document.cookie = "firstName=John;expires=Sun, 21 Jul 2019 14:00:00 IST"

The cookie string right now: firstName=John

document.cookie = "lastName=Smith;expires=Sun, 21 Jul 2019 14:00:00 IST"

The cookie string right now: firstName=John lastName=Smith

How to view Cookies?

  • Set by your website

Open Developer Tools, go to Application, and check cookies for separate domains.

  • Set by some website on your machine

In Privacy settings of your browser, select Cookies, and view individual cookies set by different websites.

The Cookie Debate

With the increased concerns regarding digital privacy, internet fraud, and confidentiality, cookies have come under much heat.

However, it is worthwhile to note that cookies cannot execute or run programs on your system. Cookies are simple text files which usually contain the name of the web browser, domain, path, expiration date, etc. There is no executable text in a cookie.

Since a cookie can only be read by the server placing it, data security becomes an issue if someone else has access to the system, or the website itself is hacked.

In the cyber security industry, it has been a common perception that third-party cookies are potentially more intrusive than first-party cookies, as they may pass the user's data to some other websites.

So it is a recommended practice to disable third-party cookies and only enable first-party cookies. The cookies can also be deleted from the machine's hard drive regularly, which may, however, lead to lesser quality of web-browsing.

Example to demonstrate working of cookies

Consider this web page where we are setting a cookie (you can download the code in a file named code.html and open it in a web browser like Google Chrome to follow along, Note: you may need to serve the page using a local server):

<!DOCTYPE html>

<head>
    <script>
        //create a cookie
        function createCookie() {
            var d = new Date();
            d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000));
            document.cookie = document.getElementById("name").value + "=" + document.getElementById("value").value + ",expires=" + d.toUTCString() + ",path=/;";
            alert(document.cookie);
        }
        
        //delete a specific cookie
        function deleteCookie() {
            var name = document.getElementById("delete").value;
            var cookie = getCookie(name);
            var d = new Date('January 01, 2001 00:00:01');
            document.cookie = name + "=,expires=" + d.toUTCString() + ",path=/;";
        }

        //get specific cookie
        function getCookie(cname) {
            var search = cname + "=";
            //to handle cookies with special characters in them use decodeURIComponent
            var decoded = decodeURIComponent(document.cookie);
            var ca = decoded.split(",");
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ')
                    c = c.substring(1);

                if (c.indexOf(name) == 0)
                    return c.substring(name.length, c.length);
            }
            return "";
        }

        //display all cookies
        function displayAllCookies() {
            alert(document.cookie);
        }
    </script>
</head>

<body>
    <form onsubmit="return createCookie()">
        Name: <input id="name" type="text">
        Value: <input id="value" type="text">
        <input type="submit" value="Create Cookie">
    </form>
    <p>
        <button type="button" onclick="displayAllCookies()">Display All Cookies</button>
    </p>
    <form onsubmit="return deleteCookie()">
        Name: <input id="delete" type="text">
        <input type="submit" value="Delete Cookie">
    </form>
</body>

</html>

Once the cookie has been set, the following alert is shown by the browser:

Create First Cookie

It will show another alert:

Create Second Cookie

The cookies will look like this in the Chrome Developer Tools. Use Ctrl+Shift+i to open the same.

Chrome Developer Tools

You can delete the cookies in the form using the delete field and you will see the changes reflected in the Chrome developer console:

Delete Cookie

Note: Some browsers, including Google Chrome, do not store cookies set by static HTML pages. Serve them on a remote server, or create a development environment like localhost and run the files on them to view the set cookies.