JavaScript Cookies: Set, Get, and Delete

Small data files called cookies are kept in the user’s browser and are frequently used to track sessions, remember user preferences, or store temporary data.

What Are Cookies?

Cookies are key-value pairs that websites save in the browser. They enable websites to preserve stateful data (such as user login status) by being sent with each HTTP request to the server. Each cookie may have properties such as path, domain, and expiration date.

Setting Cookies with JavaScript

You assign a string to a document in order to set a cookie. cookie with the following format: path=/; expires=date; name=value. The path=/ makes the cookie available throughout the website, and the expires attribute specifies when the cookie expires.

function setcookies(){
  // console.log("hi");
  let date = new Date();
  // console.log("hi2"+date);
  date.setTime(date.getTime()+(7*24*60*60*1000));
  let expire = "expire="+ date.toUTCString();
  // console.log("hi2"+expire);
  document.cookie= "username=Sujith;"+ expire + "; path=/"; // property
  alert("Cookie set : username=Sujith")
}

This function creates a cookie with the specified name and value, and optionally sets an expiration date based on the number of days.

Getting Cookies with JavaScript

The document must be parsed in order to retrieve a cookie. cookie string, which includes a list of all cookies separated by semicolons. By splitting this string, you can look up the desired cookie by name.

function getCookie(name) {
  const nameEQ = name + "=";
  const cookies = document.cookie.split(";");
  for (let cookie of cookies) {
    cookie = cookie.trim();
    if (cookie.startsWith(nameEQ)) {
      return cookie.substring(nameEQ.length);
    }
  }
  return null;
}

// Get the value of the "username" cookie
const username = getCookie("username");
console.log(username);

This function searches for a cookie by name and returns its value or null if not found.

Deleting Cookies with JavaScript

To delete a cookie, you set its expiration date to a time in the past. This causes the browser to remove it immediately.

function deletecookies(){
  // document.cookie = "username = ;" + expire + "Thu, 01 jan 1999 00:00:00 UTC; path=/";
  document.cookie = "username=; expire = Thu, 01 jan 1970 00:00:00 UTC; path=/";
  alert("cookie deleted")
}

By setting the expires attribute to a past date (e.g., 1970), the cookie is marked for deletion.

Full Example: Code

    function setcookies(){
      // console.log("hi");
      let date = new Date();
      // console.log("hi2"+date);
      date.setTime(date.getTime()+(7*24*60*60*1000));
      let expire = "expire="+ date.toUTCString();
      // console.log("hi2"+expire);
      document.cookie= "username=Sujith;"+ expire + "; path=/"; // property
      alert("Cookie set : username=Sujith")
    }

    function getCookie(name) {
      const nameEQ = name + "=";
      const cookies = document.cookie.split(";");
      for (let cookie of cookies) {
        cookie = cookie.trim();
        if (cookie.startsWith(nameEQ)) {
          return cookie.substring(nameEQ.length);
        }
      }
      return null;
    }

    // Get the value of the "username" cookie
    const username = getCookie("username");
    console.log(username);

    function deletecookies(){
      // document.cookie = "username = ;" + expire + "Thu, 01 jan 1999 00:00:00 UTC; path=/";
      document.cookie = "username=; expire = Thu, 01 jan 1970 00:00:00 UTC; path=/";
      alert("cookie deleted")
    }
  



Conclusion

A straightforward yet effective method of storing data in the browser is through JavaScript cookies. Effective user data management is possible with the help of the setCookie, getCookie, and deleteCookie functions. When using cookies, always keep security and browser compatibility in mind.

Leave a Reply