JavaScript Cookies: Create, Read and Delete

A browser cookie is a small name/value string associated with a site. In JavaScript, cookies that are available to client-side code are read and written through document.cookie.

document.cookie = 'name=Simon';
const allCookies = document.cookie;

Do not store passwords, card numbers, authentication secrets, or other sensitive values in JavaScript-readable cookies. A cookie set from JavaScript also cannot use the HttpOnly attribute; sensitive session cookies should normally be set by the server.

Table of Contents

Creating Cookies Top ↑

The original tutorial starts with a simple name/value pair. That remains the basic form:

document.cookie = 'name=' + encodeURIComponent(name);

Cookie values should be encoded before storage when they may contain spaces or special characters. When reading the value, decode it with decodeURIComponent().

Adding an Expiry Date and Other Attributes Top ↑

Without expires or max-age, a cookie is a session cookie. To keep it longer, provide an expiry date. This example keeps the original tutorial's one-day lifetime:

const expires = new Date();
expires.setDate(expires.getDate() + 1);
document.cookie = `name=${encodeURIComponent(name)}; expires=${expires.toUTCString()}; path=/javascript_tutorial; SameSite=Lax`;

The live Add Cookie demo intentionally uses a one-minute expiry, matching the original demo. Change the date calculation to control the lifetime.

path=/javascript_tutorial makes the cookie available to pages in this tutorial folder and also makes deletion predictable. SameSite=Lax is an appropriate default for this same-site learning example. Add Secure when the cookie should be sent only over HTTPS.

Original date-method concepts retained

The expiry example still uses JavaScript's Date object, getDate(), setDate(), and toUTCString().

Reading Cookies Top ↑

document.cookie returns all JavaScript-readable cookies for the current document as a semicolon-separated string. The original tutorial introduces these as JavaScript string operations and uses split(), indexOf(), and substr(). The same idea can be written more safely today by splitting, trimming, and checking the exact cookie-name prefix:

function getCookie(cookieName) {
  const prefix = `${cookieName}=`;
  const parts = document.cookie.split(';');

  for (const part of parts) {
    const cookie = part.trim();
    if (cookie.startsWith(prefix)) {
      return decodeURIComponent(cookie.slice(prefix.length));
    }
  }
  return null;
}

Trimming matters because browsers typically separate cookie pairs with a semicolon followed by a space. Checking the prefix avoids accidental partial-name matches.

Deleting Cookies Top ↑

Delete a cookie by writing the same name and path with an expiry date in the past:

document.cookie = 'name=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/javascript_tutorial; SameSite=Lax';

The path must match the path used when the cookie was created. Otherwise a different cookie can remain in place.

Working Cookie Demos Top ↑

The original demo sequence is preserved: add a name, read the stored cookie, then delete it.

Complete Working Source Top ↑

Add a cookie for one day

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Add a JavaScript cookie</title>
</head>
<body>
  <label for="name">Name</label>
  <input type="text" id="name">
  <button type="button" id="add-cookie">Add Cookie</button>
  <p id="status" aria-live="polite"></p>
  <nav><a href="add-cookies-demo.php">Add Cookies</a> | <a href="read-cookies-demo.php">Read Cookies</a> | <a href="delete-cookies-demo.php">Delete Cookies</a></nav>

  <script>
    const input = document.getElementById('name');
    const status = document.getElementById('status');

    document.getElementById('add-cookie').addEventListener('click', () => {
      const name = input.value.trim();
      if (!name) {
        status.textContent = 'Enter a name first.';
        return;
      }

      const expires = new Date();
      expires.setDate(expires.getDate() + 1);
      document.cookie = `name=${encodeURIComponent(name)}; expires=${expires.toUTCString()}; path=/javascript_tutorial; SameSite=Lax`;
      status.textContent = 'Cookie added for one day.';
    });
  </script>
</body>
</html>

Read a named cookie

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Read a JavaScript cookie</title>
</head>
<body>
  <p id="all-cookies"></p>
  <p id="welcome"></p>
  <nav><a href="add-cookies-demo.php">Add Cookies</a> | <a href="read-cookies-demo.php">Read Cookies</a> | <a href="delete-cookies-demo.php">Delete Cookies</a></nav>

  <script>
    function getCookie(cookieName) {
      const prefix = `${cookieName}=`;
      const parts = document.cookie.split(';');

      for (const part of parts) {
        const cookie = part.trim();
        if (cookie.startsWith(prefix)) {
          return decodeURIComponent(cookie.slice(prefix.length));
        }
      }
      return null;
    }

    document.getElementById('all-cookies').textContent = `Cookies: ${document.cookie || '(none)'}`;
    const name = getCookie('name');
    document.getElementById('welcome').textContent = name ? `Welcome ${name}` : 'The name cookie is not available.';
  </script>
</body>
</html>

Delete the cookie

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Delete a JavaScript cookie</title>
</head>
<body>
  <button type="button" id="delete-cookie">Delete Cookie</button>
  <p id="status" aria-live="polite"></p>
  <nav><a href="add-cookies-demo.php">Add Cookies</a> | <a href="read-cookies-demo.php">Read Cookies</a> | <a href="delete-cookies-demo.php">Delete Cookies</a></nav>

  <script>
    document.getElementById('delete-cookie').addEventListener('click', () => {
      document.cookie = 'name=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/javascript_tutorial; SameSite=Lax';
      document.getElementById('status').textContent = 'Cookie deleted.';
    });
  </script>
</body>
</html>

Common Cookie Mistakes Top ↑

  • Using document.write() after a page has loaded can replace the document. The demos now update normal DOM elements instead.
  • Comparing cookie names before trimming the leading space can cause a match to fail.
  • Deleting a cookie with the wrong path does not remove the original cookie.
  • Cookie values may need encoding and decoding.
  • JavaScript cannot read cookies marked HttpOnly.
  • Cookie availability can be affected by browser privacy settings and cookie policy.

JavaScript Document Object




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer