Cookies

JavaScript Cookies are used to store data on client side by in string format. Data stored in cookies can be used when user visit again. Cookies was developed by Netscape for Navigator Browser. When user leaves a website, browser never save anything. Cookies can save upto 4kb text data on client side.

Cookies advantages

  1. Login using cookies (without password).
  2. Product added in shopping cart.
  3. Last visited products on e-commerce sites.
  4. Ads Channels show relevant ads.
  5. Sites like Google use cookies for securities.

Cookies Limitations

  1. Can store text data only.
  2. Can store upto 4kb data only.

Create Cookies

To create cookies in javascript, we use document.cookie property and assign key/value in strings. Key and values in string must be separated by = .

Create Cookie Example


    document.cookie="name=avinash";            
    document.cookie="location=delhi";            
        

Read Cookies

"name=avinash; location=delhi"


    console.log(document.cookie);   
        

Split Cookies data

As cookies store text data in strings, to parse string data, use split() method with ; , i.e semicolon whitespace.

Cookie key is name and value is avinash

Cookie key is city and value is delhi


    document.cookie="name=avinash";            
    document.cookie="location=delhi";
    
    var cookie=document.cookie.split("; ");
    for( let i=0; i<cookie.length; i++ ){
    console.log("Cookie key is "+ cookie[i].split("=")[0] + ", and value is "+ cookie[i].split("=")[1]);
       }         
        

Store name in cookies

In the example below, we are gonna save username in session cookies. Session cookies expires when we close browser window.


Chrome block cookies on file protocol. To check cookies on file protocol, use Firefox. Or use localhost to check cookies on chrome. You can also use live server extension in VS Code project.


Cookies Expiry

By-default all cookies are session based. Cookies data expires when current session ends. Like if we close browser. To set cookie expiry, use "; expires=date" in cookies or use "; max-age=seconds" (Not supported in IE 9 and below).


cookies expires

The best way for cookies expiry is "; expires=date" is used to expire cookies data where date is in UTC String format.i.e. "Day, dd Mon YYYY HH:MM:SS GMT". For example ("Sat, 04 Feb 2023 15:01:34 GMT" )

Expiry cookie on fixed date


document.cookie="name=avinash; expires=Sat, 04 Feb 2023 15:01:34 GMT";

Expiry cookie on next day


var date=new Date();
var tomorrow=date.getTime()+(1000*60*60*24);
var exp=date.setTime(tomorrow);
document.cookie="name=avinash; expires="+ new Date(exp).toUTCString();

cookies max-age

Another but least used method is to use "; max-age=seconds" (Not supported in IE 9 and below).


document.cookie="name=avinash; max-age=10";       // 10 sec
document.cookie="name=avinash; max-age=86400";    // 1 day sec

Cookie Path & Domain

For security reasons, cookie can only be read by same domain and other pages in same directory. Thus subdomain and directories can't read cookie data.

Cookie path

path can be changes in cookies so that any page in root directory can read cookie. This is done by adding "; path"/ in the last.


    document.cookie="name=techaltum; path=/";

All directories in techaltum.com can read cookie data.

Cookie Domain

By default, only same domain can read cookie data. Even subdomain and directories can not read cookie data. To allow this, use "; domain=." in last.


document.cookie="name=techaltum; domain=techaltum.com";

This will allow subdomain like, tutorial.techaltum.com to read cookie data.


Secure Cookies

Default cookie can send data on both http and https protocols. To allow cookie data on secure domain only, use "; secure" in end.


document.cookie="name=techaltum; secure";

Only https://www.techaltum.com can read cookie data.