Cookies are small pieces of data stored on the user's browser, making it possible for websites to remember important information, such as login sessions, user preferences, and more. Managing cookies—whether it's reading, writing, or deleting them—is essential for a wide range of web development tasks. In this blog, we'll explore how to work with cookies using pure JavaScript without relying on external libraries.
What are Cookies?
Cookies store data as key-value pairs and are used by websites to remember various details about the user. Cookies can be helpful for:
- Session management (like keeping users logged in)
- Storing user preferences (such as language settings)
- Analytics and tracking purposes
Key Characteristics of Cookies:
- Cookies are stored as strings.
- Each cookie consists of a
name
and avalue
. - Cookies can have additional attributes like expiration time, path, domain, and security flags.
Now, let's dive into how to read, write, and delete cookies in JavaScript!
1. Writing a Cookie
To store data in cookies, you can use the document.cookie
property. Each time you want to write or modify a cookie, you assign it using this property.
Basic Syntax for Setting a Cookie:
document.cookie = "name=value; expires=DATE; path=/";
- name: The name of the cookie.
- value: The value of the cookie, which can be anything (text, numbers, etc.).
- expires: Sets the expiration date. If omitted, the cookie will expire when the browser is closed.
- path: Specifies the path for which the cookie is valid. Default is
/
(i.e., the entire website).
Example: Set a Cookie
function setCookie(name, value, days) {
let expires = "";
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); // Convert days to milliseconds
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/";
}
// Set a cookie that expires in 7 days
setCookie("userSession", "active", 7);
Here, we create a userSession
cookie with a value of active
and set it to expire in 7 days.
2. Reading a Cookie
When cookies are created, they are stored as a single string in the document.cookie
property, where each cookie is separated by a semicolon (;
). You can retrieve the value of a specific cookie by parsing this string.
Example: Retrieve a Cookie’s Value
function getCookieValue(name) {
const cookies = document.cookie.split(';');
for (let cookie of cookies) {
const [cookieName, cookieValue] = cookie.trim().split('=');
if (cookieName === name) {
return decodeURIComponent(cookieValue);
}
}
return null; // Cookie not found
}
// Example: Get the value of the 'userSession' cookie
const session = getCookieValue("userSession");
console.log(session); // Outputs: active
This function splits the document.cookie
string and looks for the specified cookie by name, returning its value if found.
3. Deleting a Cookie
To delete a cookie, you simply set its expiration date to a time in the past. This will remove the cookie from the browser.
Example: Delete a Cookie
function deleteCookie(name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
// Example: Delete the 'userSession' cookie
deleteCookie("userSession");
Here, we delete the userSession
cookie by setting its expiration to a past date, effectively removing it.
Handling Expiry and Other Cookie Settings
Cookies can be set with additional attributes like expiration, path, domain, and secure flags. Below is an example of setting a cookie with an expiration date and making it accessible only over HTTPS.
Example: Setting a Cookie with Expiration and Secure Attribute
function setSecureCookie(name, value, days) {
let expires = "";
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
// Adding the 'secure' flag ensures the cookie is sent only over HTTPS
document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/; secure";
}
// Set a secure cookie
setSecureCookie("secureSession", "encryptedData", 30);
Why Managing Cookies Matters
1. User Sessions
Many websites use cookies to manage user sessions. When a user logs in, a cookie is often created to track their session. Before performing user-specific actions, you can check if a session cookie exists.
2. Personalization
Cookies enable personalization by storing user preferences like language settings, theme choices, or recently viewed products. Checking for these cookies allows you to provide a seamless, personalized experience.
3. Security
Setting attributes like Secure
and HttpOnly
flags when writing cookies helps enhance security. A cookie with the Secure
flag ensures that it’s only sent over HTTPS, reducing the chances of a man-in-the-middle attack.
Complete Example: Setting, Reading, and Deleting Cookies
Here’s how you can bring it all together into a simple form interface where users can set, read, and delete cookies.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Cookie Management</title>
<style>
button { margin: 10px; }
</style>
</head>
<body>
<input type="text" id="cookieName" placeholder="Cookie Name">
<input type="text" id="cookieValue" placeholder="Cookie Value">
<input type="text" id="cookieDays" placeholder="Days to Expire">
<button onclick="createCookie()">Set Cookie</button>
<button onclick="showCookie()">Show Cookie</button>
<button onclick="deleteCookie()">Delete Cookie</button>
<script>
function setCookie(name, value, days) {
let expires = "";
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/";
}
function getCookieValue(name) {
const cookies = document.cookie.split(';');
for (let cookie of cookies) {
const [cookieName, cookieValue] = cookie.trim().split('=');
if (cookieName === name) return decodeURIComponent(cookieValue);
}
return null;
}
function deleteCookie(name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
// Create a cookie based on user input
function createCookie() {
const name = document.getElementById('cookieName').value;
const value = document.getElementById('cookieValue').value;
const days = parseInt(document.getElementById('cookieDays').value) || 7;
setCookie(name, value, days);
alert('Cookie set successfully!');
}
// Display cookie value in an alert
function showCookie() {
const name = document.getElementById('cookieName').value;
const value = getCookieValue(name);
if (value) {
alert(`Cookie value: ${value}`);
} else {
alert('Cookie not found!');
}
}
// Delete the specified cookie
function deleteCookie() {
const name = document.getElementById('cookieName').value;
deleteCookie(name);
alert('Cookie deleted successfully!');
}
</script>
</body>
</html>
Conclusion
Managing cookies is an essential aspect of modern web development. Understanding how to create, read, and delete cookies can help you provide a better user experience, manage sessions, and maintain personalization features on your website. By using native JavaScript, you have full control over how cookies behave and can enhance the security of your applications by setting appropriate flags.
Learn How to Fix "JavaScript Heap Out of Memory" in Node.js
"How to Fix the 'JavaScript Cannot Read Property of Undefined' Error"
About Muhaymin Bin Mehmood
Front-end Developer skilled in the MERN stack, experienced in web and mobile development. Proficient in React.js, Node.js, and Express.js, with a focus on client interactions, sales support, and high-performance applications.