PASSWORD RESET

Your destination for complete Tech news

How to set and unset a cookie in Javascript?

522 0
< 1 min read

To set a cookie in JavaScript, you can use the setCookie function:

function setCookie(name, value, expires, path, domain, secure) {
  var cookie = name + "=" + encodeURIComponent(value);

  if (expires) {
    cookie += "; expires=" + expires.toGMTString();
  }

  if (path) {
    cookie += "; path=" + path;
  }

  if (domain) {
    cookie += "; domain=" + domain;
  }

  if (secure) {
    cookie += "; secure";
  }

  document.cookie = cookie;
}

This function takes the following parameters:

  • name: the name of the cookie
  • value: the value to store in the cookie
  • expires: a Date object that specifies when the cookie should expire
  • path: the path on the server to which the cookie should be sent
  • domain: the domain that the cookie should be sent to
  • secure: a boolean value that specifies whether the cookie should only be sent over a secure connection (HTTPS)

To use this function, you can call it with the appropriate arguments:

setCookie("username", "John", new Date("January 1, 2025"), "/", "example.com", true);

This will set a cookie with the name “username” and the value “John”, that expires on January 1, 2025, is sent to the root path on the server, is sent to the “example.com” domain, and is only sent over a secure connection.

To unset a cookie, you can set it to expire in the past. For example:

setCookie("username", "", new Date(0), "/", "example.com", true);

This will set the “username” cookie to an empty string, with an expiration date in the past, effectively deleting the cookie.

Alternatively, you can use the removeCookie function:

function removeCookie(name) {
  setCookie(name, "", new Date(0), "/");
}

This function takes the name of the cookie as a parameter and sets the cookie to an empty string with an expiration date in the past, effectively deleting the cookie.

removeCookie("username");

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.