JavaScript Set Cookies: A Comprehensive Guide

Cookies are small pieces of data stored on a user’s browser by websites. They are commonly used to remember user preferences, track user sessions, and store other relevant information. In this article, we will explore how to set cookies using JavaScript, along with various examples and best practices.

What are Cookies?

Cookies are text files stored on the client-side (browser) by websites. They contain key-value pairs and are sent back to the server with each request. Cookies are essential for maintaining user sessions, remembering preferences, and enhancing the user experience.

Setting Cookies with JavaScript

JavaScript provides a simple way to set cookies using the document.cookie property. Here’s a basic example:

Example 1: Setting a Simple Cookie

function setCookie() {
  const expires = new Date();
  expires.setTime(expires.getTime() + 3600000); // 1 hour
  document.cookie = 'username=John Doe; expires=' + expires.toUTCString() + '; path=/';
}

setCookie();

Explanation

  • document.cookie: This is where we set the cookie. The syntax is key=value; expires=date; path=path; secure; httponly; samesite.
  • expires: The date and time when the cookie should expire. If omitted, the cookie is deleted when the browser is closed.
  • path: Specifies the path of the website where the cookie is valid. Setting it to / makes it valid for the entire domain.

Reading Cookies

To read a cookie, you can access the document.cookie property, which returns a string of key-value pairs separated by semicolons.

Example 2: Reading a Cookie

function getCookie() {
  const cookies = document.cookie.split(';');
  const cookieObj = {};

  for (let i = 0; i < cookies.length; i++) {
    const cookie = cookies[i].trim().split('=');
    cookieObj[cookie[0]] = cookie[1];
  }

  return cookieObj;
}

const userCookie = getCookie();
console.log(userCookie.username); // Output: John Doe

Explanation

  • The getCookie function splits the cookie string into individual cookies and converts them into an object for easier access.

Setting Cookies on User Interaction

You can set cookies based on user actions, such as button clicks.

Example 3: Setting a Cookie on Button Click

<!DOCTYPE html>
<html>
<head>
  <title>Set Cookie Example</title>
</head>
<body>
  <button id="setCookieBtn">Set Cookie</button>

  <script>
    document.getElementById('setCookieBtn').addEventListener('click', setCookie);

    function setCookie() {
      const expires = new Date();
      expires.setTime(expires.getTime() + 3600000); // 1 hour
      document.cookie = 'userTheme=dark; expires=' + expires.toUTCString() + '; path=/';
      alert('Cookie set successfully!');
    }
  </script>
</body>
</html>

Best Practices for Setting Cookies

  1. Set Expiry Dates: Always set an expiry date to ensure cookies are deleted after a certain period.
  2. Use Secure and HttpOnly Flags: For secure cookies, use the secure and HttpOnly flags to prevent them from being accessed by JavaScript and to ensure they are only sent over HTTPS.
  3. Keep Cookies Small: Cookies have size limits (typically around 4KB), so avoid storing large amounts of data.
  4. Use Secure Connections: Always use HTTPS when dealing with sensitive cookies to prevent data interception.

Frequently Asked Questions (FAQ)

Q1: How do I delete a cookie?

To delete a cookie, set its expiry date to a past date:

function deleteCookie() {
  const expires = new Date();
  expires.setTime(expires.getTime() - 1); // Yesterday's date
  document.cookie = 'username=; expires=' + expires.toUTCString() + '; path=/';
}

Q2: Why are my cookies not being set?

  • Ensure the browser is not blocking third-party cookies.
  • Make sure the expires date is correctly set.
  • Verify that the path is correctly specified.

Q3: Are cookies secure?

Cookies can be secure if they are set with the secure and HttpOnly flags. This prevents them from being accessed by JavaScript and ensures they are only sent over HTTPS.

Q4: Can I set multiple cookies?

Yes, you can set multiple cookies by making multiple calls to document.cookie or by separating them with semicolons:

document.cookie = 'cookie1=value1; cookie2=value2; path=/';

Common Mistakes

  1. Forgetting to Set Expiry Dates: Cookies without an expiry date are deleted when the browser is closed.
  2. Not URL-Encoding Values: Cookie values should be URL-encoded to handle special characters.
  3. Storing Sensitive Data: Avoid storing sensitive data in cookies without proper security measures.

Conclusion

Cookies are a powerful tool for enhancing user experience and maintaining sessions. By understanding how to set, read, and manage cookies in JavaScript, you can create more dynamic and personalized web applications. Always remember to follow best practices to ensure security and reliability.

Index
Scroll to Top