Cookies in JS(javascript)
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:-
1- Setting a Cookie:
document.cookie = "cookieName=cookieValue; expires=expiryDate; path=/";
cookieNameis the name of the cookie.cookieValueis the value you want to store.expires(optional) specifies the expiration date of the cookie. It should be in the formatexpires=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;
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;
}
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=/";
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

