Cookies are a way to store small amounts of data on the client side. They are useful for maintaining user sessions, storing preferences, and tracking user activity.
When a server responds to a request, it can send cookies along with the response. The browser stores these cookies.
The next time the browser sends a request to the same server, it includes the cookies in the request headers, allowing the server to recognize the user and maintain the session.
JavaScript can create, read, update, and delete cookies using the document.cookie property.
To create a cookie, you assign a string to document.cookie with the following syntax:
document.cookie = "name=value; expires=expiration_date; path=/";
• name=value: The name-value pair of the cookie.
• expires=expiration_date: Optional. The expiration date of the cookie. If omitted, the cookie is a session cookie and will be deleted when the browser is closed.
• path=/: Optional. Defines the path within the domain where the cookie is valid.
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
To read a cookie, access document.cookie and parse the string:
<script>
const cookies = document.cookie.split('; ');
const cookieObject = {};
cookies.forEach(cookie => {
const [name, value] = cookie.split('=');
cookieObject[name] = value;
});
document.write(cookieObject.username);
</script>
To update a cookie, simply set it again with the new value. Ensure you include the same name and path to overwrite the existing cookie:
document.cookie = "username=JaneDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
To delete a cookie, set its expiration date to a past date:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
<script>
// Create a cookie
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
// Read cookies
function getCookie(name) {
const cookies = document.cookie.split('; ');
const cookie = cookies.find(row => row.startsWith(name + '='));
return cookie ? cookie.split('=')[1] : null;
}
document.write("Username cookie:", getCookie("username")); // Outputs: JohnDoe
// Update the cookie
document.cookie = "username=JaneDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
document.write("Updated username cookie:", getCookie("username")); // Outputs: JaneDoe
// Delete the cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
document.write("Deleted username cookie:", getCookie("username")); // Outputs: null
</script>