What Are Cookies And How To Delete Cookies Using Javascript?
- Posted on September 14, 2023
- Technology
- By MmantraTech
- 188 Views
Introduction – What are Cookies?
Cookies are small pieces of data stored on a user's computer in the form of text files by websites they visit. Cookies play a vital role in web development for various purposes, such as maintaining user sessions and remembering user preferences. You might have experienced remember me option in login form so that you don’t type password next time you visit the same site. However, there are situations where you may need to delete cookies, either for privacy concerns or to reset certain user preferences. In this article, I am going to explain what is Cookie and how to delete cookies using JavaScript.

Understanding Cookies Elements:
Before we delve into deleting cookies, let's briefly understand how cookies work. Cookies consist of key-value pairs and have various attributes like name, value, Path, expiration date, and domain. They are stored in a user's browser and can be accessed by both the client-side (JavaScript) and server-side (backend) scripts. As you can check below image to understand Cookies Parameters.
Cookies can be persistent or temporary (Session Cookies – Browser base). It means how long Cookies files will be persisted in Client Browser (Text files stored in Client Hard Disk). This is decided by Cookies Expiration Date. You can Cookies Date that when will this Cookie will be deleted.
To delete a cookie, you need to set its expiration date to a past date. Once the browser sees that a cookie has expired, it will automatically remove it from its storage.
Here are some key points you should know about cookies in JavaScript:
-
Storage: Cookies are typically saved as text files on the user's device. Each cookie consists a name-value pair and optional attributes such as an expiration date and domain path.
-
Purpose: Cookies may have various purposes, including session management, user authentication, tracking user behavior, and remembering user preferences. But should be used with cautions as Cookies contain sensitive information.
-
Creating Cookies: You can create cookies in JavaScript using the
document.cookie
property. Here's an example:
document.cookie = "channel_name=Techmalasi; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/";
In above example, a cookie named "channel_name" is created with the value "Techmalasi" and an expiration date is set, and the cookie is made available to all pages on the website (path="/").
Reading Cookies: To read cookies, you can access the document.cookie
property. However, document.cookie
returns a string containing all cookies for the current page, so you will need to parse this string to extract specific cookie values.
const cookies = document.cookie.split('; ');
for (const cookie of cookies) {
const [name, value] = cookie.split('=');
console.log(`${name}: ${value}`);
}
Updating and Deleting Cookies:
You can update or delete a cookie by setting a new value with the same name and path, or by setting an expiration date in the past to delete the cookie.
// Update a cookie
document.cookie = "channel_name=mmantratech; expires=Dec, 18 Dec 2023 12:00:00 UTC; path=/";
// Delete a cookie
document.cookie = "channel_name=; expires=Dec, 01 Jan 1970 00:00:00 UTC; path=/";
-
Cookie Security: It's important to note that cookies are not a secure way to store sensitive information, as they are stored on the user's device and can be manipulated by the user. For secure storage of sensitive data, consider alternatives like session storage, local storage, or server-side storage.
-
Same-Origin Policy: Cookies are subject to the same-origin policy, which means that a web page can only access cookies set by the same domain.
To delete a cookie using JavaScript, follow these steps:
- Identify the Cookie to Delete: First, you need to know the name of the cookie you want to delete. You cannot delete a cookie without knowing its name.
- Set the Cookie's Expiration Date: Use JavaScript to set the expiration date of the cookie to a date in the past. This essentially tells the browser to remove the cookie.
Below is the sample JavaScript function to delete a cookie by name:
function deleteCookie(cookieName) {
// Set the expiration date to a past date
document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
}
Let's understand this code:
- "document.cookie" is a property that allows you to access and modify cookies for the current document.
- "${cookieName}=" is setting the cookie with the specified name to an empty value.
- "expires=Thu, 01 Jan 1970 00:00:00 UTC;" sets the expiration date to a date in the past (January 1, 1970).
- "path=/;" specifies the path for which the cookie is valid. Setting it to `/` makes the cookie valid for the entire website.
Another way to delete Cookie :
document.cookie = "auth_token=; Max-Age=0; path=/; domain=yourdomain.in;";
Full Practical Code Example :
<!DOCTYPE html>
<html>
<head>
<title>TechMalasi - Cookies Example by Mmantratech</title>
</head>
<body>
<h1>Cookie Example</h1>
<p id="cookieStatus">Cookies:</p>
<button onclick="createCookie()">Create Cookie</button>
<button onclick="deleteCookie()">Delete Cookie</button>
<script>
// Function to create a cookie
function createCookie() {
const cookieName = "mmantratech";
const cookieValue = "techmalasi";
const expirationDate = new Date();
expirationDate.setHours(expirationDate.getHours() + 1); // Cookie expires in 1 hour
document.cookie = `${cookieName}=${cookieValue}; expires=${expirationDate.toUTCString()}; path=/`;
updateCookieStatus();
}
// Function to delete a cookie
function deleteCookie() {
const cookieName = "mmantratech";
// Set the expiration date in the past to delete the cookie
const expirationDate = new Date();
expirationDate.setHours(expirationDate.getHours() - 1);
document.cookie = `${cookieName}=; expires=${expirationDate.toUTCString()}; path=/`;
updateCookieStatus();
}
// Function to update the displayed cookie status
function updateCookieStatus() {
const cookies = document.cookie;
const cookieStatusElement = document.getElementById("cookieStatus");
cookieStatusElement.textContent = `Cookies: ${cookies}`;
}
// Initial update of cookie status
updateCookieStatus();
</script>
</body>
</html>
Let's understand above example:
-
We have a webpage with a title, some text, and two buttons: "Create Cookie" and "Delete Cookie."
-
When you click the "Create Cookie" button, the
createCookie()
JavaScript function is called. This function sets a cookie named "username" with the value "John" and an expiration time of 1 hour from the current time. It then callsupdateCookieStatus()
to display the current cookie status. -
When you click the "Delete Cookie" button, the
deleteCookie()
JavaScript function is called. This function deletes the "mmantratech" cookie by setting its expiration time to a past date. It also callsupdateCookieStatus()
to update the displayed cookie status. -
The
updateCookieStatus()
function retrieves all cookies usingdocument.cookie
and updates the content of the<p>
element with the ID "cookieStatus" to display the current cookie status.
Conclusion :
Cookies are essential for web development but may need to be deleted under certain circumstances. Cookies are fundamental to web development for managing user state and preferences, but they should be used carefully, particularly when dealing with user privacy and sensitive information. Modern web development often relies on alternatives like Web Storage (localStorage and sessionStorage) and IndexedDB for client-side data management. I hope I could able to mkae you uderstand the basic idea about Cookies and its deletion process.
Write a Response