DEV Community

DIWAKARKASHYAP
DIWAKARKASHYAP

Posted on

What is Cookies | Cookies in JS (javascript)

JavaScript cookies are utilized by websites to store small data fragments on a user's browser. These fragments serve the purpose of retaining user-related information or monitoring their browsing behavior. As a standard practice, cookies accompany each website request, enabling the server to access the stored data.

Here's how you can work with cookies in JavaScript:-

1- Setting a Cookie:

document.cookie = "cookieName=cookieValue; expires=expiryDate; path=/";
Enter fullscreen mode Exit fullscreen mode

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.

2- Getting a Cookie:

var cookies = document.cookie;
Enter fullscreen mode Exit fullscreen mode

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

3- Parsing and extracting a specific cookie:

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;
}
Enter fullscreen mode Exit fullscreen mode

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

4- Deleting a cookie:

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=/";
Enter fullscreen mode Exit fullscreen mode

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

Top comments (2)

Collapse
 
blueberry077 profile image
Marc-Daniel DALEBA

I really thought you were talking about real cookies.
Actually this is an interesting tutorial. (o^▽^o).

Collapse
 
diwakarkashyap profile image
DIWAKARKASHYAP • Edited

Thanks for your words! I am glad you find it useful!,
are you developer ?
if you need any blog related programming, development, opensource then please comment