Introduction to HTTP Cookies

May 9, 2021

I heard the british use biscuits instead of cookies...weird.


What are Cookies

Cookies, more properly called HTTP cookies, are small bits of data stored as text files on a browser. Cookies associate bits of data to a specific user. Cookies are mainly used for three purposes:


Session management

Logins, game scores, or anything else the server should remember.


Personalization

User preferences, themes, and other settings. For example, a user's preferences such as language and preferred theme could be saved for future sessions.


Tracking

Recording and analyzing user behavior. When a user visits a shopping website and searches for an item, the item gets saved in their browser history. Cookies can read browsing history so similar are shown to the user next time they visit.


Types of Cookies


Session cookies

Session cookies, also known as 'temporary cookies', help websites recognise users and the information provided when they navigate through a website. Session cookies only retain information about a user's activities for as long as they are on the website. Once the web browser is closed, the cookies are deleted.


Permanent cookies

Permanent cookies are also known as 'persistent cookies'. They remain in operation even after the web browser has closed. For example they can remember login details and passwords so web users don't need to re-enter them every time they use a site.


Third-party cookies

Third-party cookies are installed by third-parties with the aim of collecting certain information from web users to carry out research into, for example, behaviour, demographics or spending habits. They are commonly used by advertisers who want to ensure that products and services are marketed towards the right target audience.


Flash cookies

Flash cookies are also known as 'super cookies'. They are independent from the web browser. They are designed to be permanently stored on a user's computer. These types of cookies remain on a user's device even after all cookies have been deleted from their web browser.


Zombie cookies

Zombie cookies are a type of flash cookie that are automatically re-created after a user has deleted them. This means they are difficult to detect or manage. They are often used in online games to prevent users from cheating, but have also been used to install malicious software onto a user's device.


Secure Cookies

Only HTTPS websites can set secure cookies, i.e., cookies with encrypted data. Mostly, the checkout or payment pages of e-commerce websites have secure cookies to facilitate safer transactions. Similarly, online banking websites are required to use secure cookies for security reasons.


Creating Cookies with Vanilla JavaScript

NOTE: For the code below to work, your browser has to have local cookies support turned on.

JavaScript can create, read, and delete cookies with the document.cookie property.With JavaScript, a cookie can be created by setting a cookie-name and cookie-value as shown below.


document.cookie = "username=LindaOjo";


The cookie-name above is username and it's corresponding value is LindaOjo

You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed:


document.cookie = "username=LindaOjo; expires=Wed, 1 Oct 2022 12:00:00 UTC";


With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.


document.cookie = "username=LindaOjo; expires=Wed, 1 Oct 2022 12:00:00 UTC; path=/";


Handling Cookies using just vanilla JavaScript can get tedious real quick that's why I prefer using the JavaScript Cookie Package


Handling Cookies with JavaScript Cookie Package

JavaScript Cookie is a simple lightweight JavaScript API for handling cookies. It works on all browsers, accepts any character, heavily tested and requires no dependency. Awesome!


Installation

Run the command below in your root folder.


npm install js-cookie --save


Cookie Attributes

  • Expire: define when the cookie will be removed. Value can be a Number which will be interpreted as days from time of creation or a Date instance.

  • Path: a String indicating the path where the cookie is visible.

  • Domain: a String indicating a valid domain where the cookie should be visible. The cookie will also be visible to all subdomains.

  • Secure: Either true or false, indicating if the cookie transmission requires a secure protocol (https).


Create a cookie

We can create a cookie that valid across the entire website by providing the name and the value as shown below.


import Cookies from 'js-cookie'; Cookies.set('name', 'value');


We can specify how long it takes for a cookie to expire by passing an object that contains the number of days before expiration as the third argument in the Cookie.set method. The cookie that's created below expires after 7 days. By default, a cookie is removed when the user closes the browser.


import Cookies from 'js-cookie'; Cookies.set('name', 'value', { expires: 7 });


Next,We can create an secure expiring cookie that's only valid to the path of the current page. The path is add to the previous Object which contains the expiration date.


Cookies.set('name', 'value', { expires: 7, path: '', secure: true });


Read cookie

The point of creating cookies is so we can use them later. We can access already existing cookies using the Cookie.get method. Let's create and read a real cookie called 'theme'.


import Cookies from 'js-cookie'; Cookies.set('theme', 'dark'); Cookies.get('theme') // => 'dark'


You can also update a cookie by overriding it's value


Cookies.set('theme', 'light');


Now the theme cookie has a value of 'light'. We can get all cookies present at once by calling Cookies.get method without passing in any arguments. An object containing all cookies is returned in this case.


Cookies.get(); // => { theme: 'light' }


Delete cookie

You can delete cookies that are globally accessible running the Cookie.remove method with just the first argument which is value


Cookies.remove('theme');


Note: when deleting a cookie and you are not relying on the default attributes, you must pass the exact same path and domain attributes that were used to set the cookie. Let us set and delete a cookie valid to the path of the current page as an example.


Cookies.set('direction', 'north', { path: '' }); Cookies.remove('direction'); // fail! Cookies.remove('direction', { path: '' }); // removed!


That's a wrap! This is a simple introduction to HTTPS Cookies,I trust you learnt a lot.

Created by Linda Ojo Taiwo