To create and manage cookies for storing user data using JavaScript, you can follow these steps:
Set a cookie: To create a new cookie, you can use the document.cookie
property. The syntax for setting a cookie is document.cookie = "cookieName=cookieValue; expires=expirationDate; path=pathValue;";
. Here's an example:
document.cookie = "username=John Doe; expires=Thu, 01 Jan 2022 00:00:00 UTC; path=/;";
In the above example, a cookie named "username" is being set with the value "John Doe". It will expire on January 1, 2022, and the cookie will be accessible on the entire website.
Get a cookie: To retrieve the value of a cookie, you can access the document.cookie
property. This property stores all the cookies associated with the current domain. However, document.cookie
returns a single string with all cookie values concatenated. You can create a function to extract the value of a specific cookie. Here's an example:
function getCookie(cookieName) {
const cookieStrings = document.cookie.split("; ");
for (let i = 0; i < cookieStrings.length; i++) {
const cookie = cookieStrings[i].split("=");
if (cookie[0] === cookieName) {
return cookie[1];
}
}
return "";
}
// Usage
console.log(getCookie("username")); // Output: John Doe
The getCookie
function splits document.cookie
by "; " to separate individual cookies. Then, each cookie is split by "=" to extract the name and value. If the cookie name matches the desired name, its value is returned.
Update a cookie: To update an existing cookie, you can use the same document.cookie
property. Simply set the cookie again with the updated value and any desired options. Here's an example:
document.cookie = "username=Jane Doe; expires=Thu, 01 Jan 2023 00:00:00 UTC; path=/;";
This code updates the value of the "username" cookie to "Jane Doe" and extends the expiration date to January 1, 2023.
Delete a cookie: To delete a cookie, you need to set its expiration date to a past date. Here's an example:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
This code removes the "username" cookie by setting its expiration date to January 1, 1970.
It's important to note that cookies are limited in size and can be accessed and manipulated by the client. Therefore, you should never store sensitive information like passwords or personal data in cookies.