Skip to main content

Command Palette

Search for a command to run...

Cookies in JS(javascript)

Published
2 min read
D

As a passionate developer, I thrive on acquiring new knowledge. My journey began with web development, and I am now actively engaged in open source contributions, aiding individuals and businesses.

JavaScript cookies play a vital role in web development by enabling websites to store small data pieces on users' browsers. These data bits serve the purpose of remembering user information and tracking their browsing activity. As a result, cookies are included in every request sent to the website, facilitating the retrieval of stored data by the server.

Here's how you can use cookies in Javascript:-

document.cookie = "cookieName=cookieValue; expires=expiryDate; path=/";
  • cookieName is the name of the cookie.

  • cookieValue is the value you want to store.

  • expires (optional) specifies the expiration date of the cookie. It should be in the format expires=Thu, 01 Jan 2023 00:00:00 GMT.

  • path (optional) sets the scope of the cookie. By default, it applies to the current path.

var cookies = document.cookie;

The document.cookie property contains all the cookies as a string. You'll need to parse and extract the specific cookie you want.

function getCookie(name) {
  var cookieValue = null;
  var cookies = document.cookie.split(';');
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i].trim();
    if (cookie.startsWith(name + '=')) {
      cookieValue = cookie.substring(name.length + 1);
      break;
    }
  }
  return cookieValue;
}

You can use the getCookie function to extract the value of a specific cookie by providing its name.

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

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

Cookies are limited in size and can be accessed by client-side code. Sensitive information should not be stored in cookies. Modern web development uses local storage or session storage for data persistence.

if you want to know about Local and session storage click here ,i have another blog on it

Thank you for reading this blog, follow me on Twitter, I regularly share blogs and post on Javascript, React, Web development and opensource contribution

Twitter- https://twitter.com/Diwakar_766

Github- https://github.com/DIWAKARKASHYAP

More from this blog

My first blog

40 posts

As a passionate developer, I thrive on acquiring new knowledge. My journey began with web development, and I am now actively engaged in open source contributions, aiding individuals and businesses.