JavaScript Cookies Tutorial for Beginners

Welcome to this JavaScript cookies tutorial, your beginner-friendly guide to understanding and using cookies in JavaScript! Cookies let you store small pieces of data in a user’s browser, like user preferences or session information. This tutorial explains cookies, how to create, read, and delete them, and includes practical examples to get you started.

What Are JavaScript Cookies?

Cookies are small text files stored in a user’s browser to save data, such as login details, user settings, or website preferences. This JavaScript cookies tutorial shows you how to manage cookies to enhance website functionality and user experience.

Why Use Cookies?

  • Save User Data: Store preferences, like theme or language choices.
  • Session Management: Track user sessions for logins or shopping carts.
  • Personalization: Remember user choices for a tailored experience.

Related: New to JavaScript? Check our JavaScript Events Tutorial for more interactivity tips.

How Cookies Work

Cookies are stored as key-value pairs in the browser via the document.cookie property. Each cookie has a name, value, and optional attributes like expiration date or path. In this JavaScript cookies tutorial, we’ll focus on:

  1. Creating/Setting a cookie.
  2. Reading a cookie.
  3. Deleting a cookie.

Key Concepts

  • Cookie String: A string like name=value; expires=date; path=/.
  • Expiration: When the cookie expires (default: session ends).
  • Path: The URL path where the cookie is available (e.g., / for the whole site).

Setting a Cookie

Use document.cookie to create or update a cookie. You assign a string with the cookie’s name, value, and optional attributes.

Syntax for Setting a Cookie

document.cookie = "name=value; expires=date; path=/";
  • name=value: The cookie’s key and value.
  • expires=date: When the cookie expires (in UTC format).
  • path=/: Makes the cookie available site-wide.

Example 1: Creating a Simple Cookie

Let’s set a cookie to store a username.

<button id="setCookie">Set Cookie</button>

<script>
  function setCookie() {
    document.cookie = "username=Alice; expires=Fri, 30 May 2025 12:00:00 UTC; path=/";
    alert('Cookie set: username=Alice');
  }

  const button = document.getElementById('setCookie');
  button.addEventListener('click', setCookie);
</script>
  • Clicking the button sets a cookie username=Alice that expires in a week.
  • The path=/ makes it accessible across your site.
  • Try this in an HTML file and check the cookie in your browser’s Developer Tools (Application > Storage > Cookies).

Reading a Cookie

To read cookies, access document.cookie, which returns a string of all cookies. You’ll need to parse it to find the desired cookie.

Syntax for Reading Cookies

let cookies = document.cookie; // Returns all cookies as a string

Example 2: Reading a Cookie

Let’s read the username cookie and display it.

<button id="readCookie">Read Cookie</button>
<p id="output">No cookie read yet.</p>

<script>
  function getCookie(name) {
    let cookies = document.cookie.split('; ');
    for (let cookie of cookies) {
      let [key, value] = cookie.split('=');
      if (key === name) return value;
    }
    return '';
  }

  const button = document.getElementById('readCookie');
  const output = document.getElementById('output');
  button.addEventListener('click', function() {
    let username = getCookie('username');
    output.textContent = username ? `Username: ${username}` : 'No username cookie found';
  });
</script>
  • The getCookie function splits document.cookie into key-value pairs and finds the username.
  • Clicking the button displays the cookie’s value or a message if it’s not found.

Deleting a Cookie

To delete a cookie, set its expiration date to the past.

Syntax for Deleting a Cookie

document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";

Example 3: Deleting a Cookie

Let’s delete the username cookie.

<button id="deleteCookie">Delete Cookie</button>

<script>
  function deleteCookie(name) {
    document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;
    alert(`Cookie ${name} deleted`);
  }

  const button = document.getElementById('deleteCookie');
  button.addEventListener('click', function() {
    deleteCookie('username');
  });
</script>
  • Sets the cookie’s expiration to 1970, effectively deleting it.
  • Check Developer Tools to confirm the cookie is gone.

Common Cookie Attributes

In this JavaScript cookies tutorial, you’ll often use these attributes:

  • expires: Sets the expiration date (e.g., expires=Fri, 30 May 2025 12:00:00 UTC).
  • path: Defines where the cookie is accessible (e.g., path=/ for site-wide).
  • domain: Specifies the domain (e.g., domain=example.com).
  • secure: Ensures the cookie is sent only over HTTPS.
  • SameSite: Controls cross-site sharing (e.g., SameSite=Strict).

Example 4: Cookie with Attributes

Set a secure cookie with a specific path.

<button id="setSecureCookie">Set Secure Cookie</button>

<script>
  function setSecureCookie() {
    document.cookie = "theme=dark; expires=Fri, 30 May 2025 12:00:00 UTC; path=/; secure; SameSite=Strict";
    alert('Secure cookie set: theme=dark');
  }

  const button = document.getElementById('setSecureCookie');
  button.addEventListener('click', setSecureCookie);
</script>
  • Sets a theme cookie with secure and SameSite=Strict for security.

Common Mistakes to Avoid

  • No Expiration: Without expires, cookies are session-only and vanish when the browser closes.
  • Incorrect Parsing: Ensure getCookie handles empty or malformed cookies.
  • Path Issues: Use path=/ for site-wide access, or specify a path carefully.
  • Security: Use secure and SameSite for sensitive data.

Practice Challenge: Save and Display a Preference

Create a button that saves a user’s preferred color as a cookie and another to display it.

<button id="saveColor">Save Color</button>
<button id="showColor">Show Color</button>
<p id="colorOutput">No color preference yet.</p>

<script>
  function setCookie(name, value, days) {
    let date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    document.cookie = `${name}=${value}; expires=${date.toUTCString()}; path=/`;
  }

  function getCookie(name) {
    let cookies = document.cookie.split('; ');
    for (let cookie of cookies) {
      let [key, value] = cookie.split('=');
      if (key === name) return value;
    }
    return '';
  }

  const saveButton = document.getElementById('saveColor');
  const showButton = document.getElementById('showColor');
  const output = document.getElementById('colorOutput');

  saveButton.addEventListener('click', function() {
    setCookie('color', 'blue', 7);
    output.textContent = 'Color preference saved: blue';
  });

  showButton.addEventListener('click', function() {
    let color = getCookie('color');
    output.textContent = color ? `Your color: ${color}` : 'No color preference found';
  });
</script>
  • Saves a color cookie for 7 days and displays it on demand.

Happy coding! Explore more tutorials on our JavaScript Learning Hub.

Scroll to Top