Handling Cookies with JavaScript

You can use JavaScript to read, create, update and delete cookies in your site. JavaScript uses the document object and cookie property to handle cookies. Let us understand one by one all operations done with the cookies using JS. All the code is executed using the HTML, CSS and JS IDE of GFG so, to test the code copy the below JS code under a script tag.

1. Create a Cookie:

You can set the cookie using “document.cookie” property the values to be passed are name, value, expiry date and path. In the below code a myCookie() is called by passing the name, value and expiry days of the cookie. Its uses the date object to set the expiry date of the cookie in UTC.

Javascript




function myCookie(name, value, days) {
  
            // variable used to store expire date in UTC
            let expires = ""
              
            // checks if user passed the expiry days
            if (days) { 
                   const date = new Date();
                   
                 // set the date object time to the expiry time in miliseconds
                    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));  
                   
                 // sets the approprate cookie format which 
                 // will be used in creation of the cookie
                   expires = "; expires=" + date.toUTCString(); 
            }
              
            // creates the cookie
            document.cookie = name + "=" + value + expires + "; path=/"
        }
          
 myCookie('GFG', 'Hello World', 2); 
 // This creates a cookie named 'GFG' with the 
 // value 'Hello World' that expires in 2 days.
         


Output:

My custom created Cookie

2. Read a Cookie:

You can use “document.cookie” property to get all the cookies and there value. It will return all cookies with there values separated by ‘;’ in the format cookieName=value; .

Use the below code to get all cookies at once.

Javascript




let allCookies = document.cookie;
console.log(allCookies);


Output:

All cookies of GFG

You can also get the cookie with respect to a given name. We create a readCookie() which takes a name parameter. The “document.cookie” property returns all the cookies name with value so, to get a particular cookie we first split the cookies into an array of string of cookieName=value. The function then removes any initial space in the strings and then check for the name of the cookie if its matched then it returns the value of the cookie.

Javascript




function readCookieWithName(name) {
  
    // Your cookie name with = sign 
    const nameEQ = name + "="
      
    // Spilits all the cookies to only name=value string array
    const cookies = document.cookie.split(';'); 
    for(let i = 0; i < cookies.length; i++) {
        let cookie = cookies[i];
        while (cookie.charAt(0) === ' '
          
         // Removes the starting space in each string of the array.
          cookie = cookie.substring(1, cookie.length);  
        if (cookie.indexOf(nameEQ) === 0) 
          
           // Returns only the value part of the matched cookie name
          return cookie.substring(nameEQ.length, cookie.length);
    }
    return null;
}
  
// Reading a cookie of GFG site with name gfg_theme
let mycookie = readCookieWithName('gfg_theme'); 
console.log(mycookie); /


Output:

Reading Cookie named gfg_theme

3. Update a Cookie:

You can edit a cookies name, value, path and expiry days using the document.cookie property. Just have the updated value in sting and pass it into document.cookie property.

Javascript




function updateCookie(name, value, days) {
      
    // Variable use to store the expiry date
    const expires = new Date();  
      
    // Sets the expiry date with respect to current time
    expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000)); 
      
    // Updates the cookie with new values
    document.cookie = `${name}=${value};expires=${expires.toUTCString()};path=/`; 
}
updateCookie('GFG', 'HI GFG', 10); 


Output:

Updating GFG cookie

4. Delete a Cookie:

You can delete the cookie by setting the expires parameter to a past date. The function below just take the cookie name to be deleted and set the cookie name to a empty value and sets the expiry time to be some past date.

Javascript




function deleteCookie(name) {
    // Changes the value to empty string and set the expiry time to a past date
    document.cookie = `${name}=;expires=Thu, 01 Jan 2000 00:00:00 UTC;path=/;`; 
}
deleteCookie('GFG'); // On function call it deletes the GFG cookie.


Output: You can see GFG cookie is not present in the image below.

Deleted GFG cookie

View, Edit and Delete Cookies in Microsoft Edge Browser

Application Tab is a tool provided by Edge to view, edit, and delete cookies. Cookies are small files storing user-related information that is being stored by the web server using the client browser to make the website dynamic, i.e., the same site but different UI or functionality for different users.

For example, if we visit a site and by default, it is in light mode, we change it to dark mode. The next time we visit the site, it presents itself in dark mode because the user theme choice is stored as a cookie.

Similar Reads

How to view cookie information:

The Cookies pane is present in the Application Tab in developer tools. To open it follow these steps:...

Understanding Various Options To Filter and Delete Cookies:

Lets move from left to right to understand the various options provided to us....

Understanding Various Fields and Edit them:

1. Fields of a Cookie:...

Handling Cookies with JavaScript:

You can use JavaScript to read, create, update and delete cookies in your site. JavaScript uses the document object and cookie property to handle cookies. Let us understand one by one all operations done with the cookies using JS. All the code is executed using the HTML, CSS and JS IDE of GFG so, to test the code copy the below JS code under a script tag....

Conclusion

...