Mastering Cookies for Enhanced Web Experience and Security

Introduction to Cookies

Cookies are small pieces of data stored by a user’s web browser while they are browsing a site. They are commonly used for remembering information about the user, such as login status, personalization preferences, and tracking behavior for analytics purposes.

Setting a Cookie

To set a cookie, you can use the document.cookie property. Here’s a simple example:

  document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";

Reading a Cookie

You can read a cookie by accessing the document.cookie property, which returns all cookies in a single string:

  const cookies = document.cookie;
  console.log(cookies); // "username=JohnDoe; expires=Fri, 31 Dec 2023 23:59:59 GMT"

Updating a Cookie

To update a cookie, you just need to set a new value for it. The name must stay the same:

  document.cookie = "username=JaneDoe; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";

Deleting a Cookie

To delete a cookie, set its expiration date to a past date:

  document.cookie = "username=JohnDoe; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";

Checking for Cookies Enabled

To check if cookies are enabled in the browser, try setting a test cookie and then reading it:

  document.cookie = "testcookie=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
  const cookiesEnabled = document.cookie.indexOf("testcookie=") != -1;
  if (cookiesEnabled) {
    console.log("Cookies are enabled");
  } else {
    console.log("Cookies are not enabled");
  }

A Practical Example: Login App Using Cookies

Combining the above methods, here is a simple login application example using cookies:

  function setCookie(name, value, days) {
    const d = new Date();
    d.setTime(d.getTime() + (days*24*60*60*1000));
    const expires = "expires=" + d.toUTCString();
    document.cookie = name + "=" + value + ";" + expires + ";path=/";
  }

  function getCookie(name) {
    const cname = name + "=";
    const decodedCookie = decodeURIComponent(document.cookie);
    const ca = decodedCookie.split(';');
    for(let i = 0; i < ca.length; i++) {
      let c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(cname) == 0) {
        return c.substring(cname.length, c.length);
      }
    }
    return "";
  }

  function checkLogin() {
    const user = getCookie("username");
    if (user != "") {
      alert("Welcome again " + user);
    } else {
      user = prompt("Please enter your name:", "");
      if (user != "" && user != null) {
        setCookie("username", user, 30);
      }
    }
  }

  checkLogin();

This example demonstrates how to set a cookie upon login, retrieve it upon return, and provide a personalized message.

Hash: 2f0030c535193fc164e4e2b5371e8e676510cf0a64b2689d9aba6533e6ddea82

Leave a Reply

Your email address will not be published. Required fields are marked *