Author: Hussain Mir Ali

I am interested in web and mobile technologies.

If you have any questions or feedback then message me at

Data Persistence in Browser with JavaScript Part-3

Cookies work on the principle of key-value pairs to store data. Usually cookies have been used to persist user information like authentication tokens from the server. The authentication token is then used to send requests to the server. 


This attribute sets the persistence of a cookie which is equal to the difference between specified time and current time. If not set then the cookie only lasts until the browser is open.

Setting this attribute allows cookies to be sent to the server only on encrypted channel like HTTPS. But it works best if the response from the server containing the cookie was also sent on an encrypted channel.

The path attribute can be used to set validity of domain for a specific sub-folder of a domain. For instance if the 'domain' attribute is set to '' then the cookie can be set for the sub-folder '' by setting 'path' attribute to '/en-ca'. 

The 'domain' attribute sets the validity of the cookie for a certain domain. For instance if the 'domain' attribute is set to '' then all its sub-domains like and other like it will be able to read cookie information. Also the cookie wil be valid for the domain's sub-folders like '' and others like it. So the 'domain' attribute should be specifically set for sub-folders and sub-domains.

Setting this attribute will disallow client-side scripts to access the cookie. This is to prevent Cross Site Scripting with malicious scripts. It should be noted that this is only a preventive measure and not a bullet proof method.

CRUD operations with cookies:

document.cookie = "username=test2017; expires=Mon, 18 Dec 2017 12:00:00 UTC; path=/";
The above code creates a cookie that stores information about 'username', has a specific expiry time stored in the 'expires' key and also has the 'path' information.

let cookie_information = document.cookie;

console.log(cookie_information); //username=test2017
To read a cookie one can simply set a variable to 'document.cookie' this will return the information sorted in the cookie that has not yet expired.

document.cookie = "username=test2018; expires=Mon, 17 Dec 2018 12:00:00 UTC; path=/";
Updating a cookie is similar to creating a cookie. But this time the keys 'username' and 'expires' can be updated. 

document.cookie = "username=test2018; expires=Mon, 17 Dec 2016 12:00:00 UTC; path=/";
To delete a cookie simply update it by setting the 'expires' key to a previous date from current date. When the 'expires' key has an older date then cookie will automatically be deleted.