How to Read, Write, and Delete Cookies in JavaScript

Muhaymin Bin Mehmood

Muhaymin Bin Mehmood

· 8 min read
How to Read, Write, and Delete Cookies in JavaScript Banner Image
How to Read, Write, and Delete Cookies in JavaScript Banner Image

Table of Contents:

  1. What are Cookies?
  2. Key Characteristics of Cookies
  3. Writing a Cookie
  4. Reading a Cookie
  5. Deleting a Cookie
  6. Handling Expiry and Other Cookie Settings
  7. Why Managing Cookies Matters
  8. Complete Example: Setting, Reading, and Deleting Cookies
  9. Conclusion
  10. FAQs

What are Cookies?

Cookies are small pieces of data that websites store on a user's browser to help remember certain aspects of their interaction with the site. These tiny files can hold a variety of information like user preferences, session identifiers, or tracking data, and they enable websites to provide a personalized and efficient browsing experience.

In technical terms, cookies are stored as key-value pairs, where the key is the name of the cookie, and the value is the data that the website wants to store. The data saved in cookies can persist for a specified amount of time or until the browser is closed, depending on how the cookie is configured.

Cookies are widely used in web development for various purposes, including:

  • Session management: Keeping users logged in between pages or visits.
  • Personalization: Storing language preferences or themes.
  • Analytics: Tracking user activity across pages or websites for better insights.
  • Advertising: Serving personalized ads based on user behavior.

Key Characteristics of Cookies

Cookies may seem like simple text strings, but they come with certain attributes that define their behavior. Let’s go over the essential characteristics of cookies:

  • Name and Value:
    Every cookie consists of a unique name and a value. The name is the identifier, and the value can hold any string data like session identifiers, user preferences, or even encoded objects.
  • Expiration:
    Cookies can either be persistent or session-based. A session cookie expires when the browser is closed, while a persistent cookie is stored with an expiration date, which you can set.
  • Path and Domain:
    These attributes control where a cookie is accessible. By default, cookies are valid for the entire domain, but you can restrict them to specific paths (e.g., /user).
  • Secure and HttpOnly:
    These flags add security by restricting where and how cookies are sent. The Secure flag ensures that cookies are only sent over HTTPS, and the HttpOnly flag prevents JavaScript from accessing the cookie, making it safer from XSS attacks.

Now, let's dive into how to read, write, and delete cookies in JavaScript!

Writing a Cookie

In JavaScript, you can write a cookie by setting the document.cookie property. This is an easy way to store data in the user’s browser and track information like login states or preferences.

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>

Security Best Practices for Cookies

  • Use Secure Flag:
    Always set the Secure flag to ensure cookies are only sent over HTTPS connections.
  • Set HttpOnly Flag:
    Prevent JavaScript from accessing the cookie data by setting the HttpOnly flag.
  • Use SameSite Attribute:
    Set the SameSite attribute to prevent cookies from being sent with cross-site requests, mitigating CSRF attacks.
  • Short Expiry Times for Sensitive Cookies:
    For security-sensitive cookies, set a short expiration time and refresh the cookie periodically.

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.

FAQs

  • What are cookies used for in web development?
    Cookies are used for storing session data, user preferences, tracking user activities, and personalizing the user experience.
  • How do I make cookies secure?
    Use the Secure and HttpOnly flags to protect cookies. The Secure flag ensures that cookies are sent over HTTPS, and the HttpOnly flag prevents access to cookies via JavaScript.
  • Can cookies be deleted?
    Yes, cookies can be deleted by setting their expiration date to a time in the past.
  • How can I retrieve a cookie's value?
    You can retrieve a cookie by splitting the document.cookie string and searching for the cookie's name.
  • Are cookies shared across websites?
    Cookies are only accessible to the domain that created them, ensuring that one website can't access cookies set by another.
  • What happens if a cookie doesn't have an expiration date?
    Cookies without an expiration date are considered session cookies and are automatically deleted when the browser is closed.
  • How long do cookies last?
    Cookies can last as long as their expiration date is set. If no expiration date is set, they last until the browser is closed.
  • Can cookies be used for tracking?
    Yes, cookies are commonly used for tracking user behavior on websites for analytics and targeted advertising.
  • Are cookies safe to use?
    Cookies are safe when managed correctly with proper security flags, such as Secure and HttpOnly.
  • What is the SameSite attribute for cookies?
    The SameSite attribute is used to control whether cookies are sent along with cross-site requests, providing protection against CSRF attacks.
Muhaymin Bin Mehmood

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.

Join our newsletter

Subscribe now to our newsletter for regular updates.

Copyright © 2025 Mbloging. All rights reserved.