Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

JavaScript Cookies

Updated on Nov 25, 2024
By Mari Selvan
πŸ‘οΈ 71 - Views
⏳ 4 mins
πŸ’¬ 1 Comment
JavaScript Cookies

Photo Credit to CodeToFun

Introduction

Cookies are small text files that store information about the user's interaction with a website. In JavaScript, cookies can be created, modified, and accessed using simple methods. They are often used for session management, personalization, and tracking user behavior on websites.

What Are Cookies?

Cookies are data stored on the user's device by their browser. They contain key-value pairs of data and can be used to remember information between page requests or across browser sessions. While they are often used to track user activities, cookies also play an important role in login sessions, user preferences, and saving form data.

Key Features of Cookies

  • Small Size: Cookies are lightweight, usually limited to around 4KB of data per cookie.
  • Expiration: Cookies can be set to expire at a certain time or persist until the browser is closed.
  • Scope: Cookies can be scoped to a specific domain and path, which defines their availability to different parts of the website.
  • Accessibility: Both the server and client-side JavaScript can read and modify cookies.

Setting Cookies in JavaScript

In JavaScript, cookies are set using the document.cookie property. A basic cookie can be created by assigning a key-value pair to this property:

JavaScript
Copied
Copy To Clipboard
document.cookie = "username=JohnDoe";

You can also add additional parameters, like expiration date, to control how long the cookie will be stored:

JavaScript
Copied
Copy To Clipboard
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 12:00:00 UTC";

Cookie Storage Limitations

Cookies have limitations in terms of storage capacity and the number of cookies per domain:

  • Size: Each cookie is limited to about 4KB in size.
  • Number: Browsers generally limit the number of cookies that can be stored per domain (typically 20-50).
  • Cross-Origin Restrictions: Cookies are restricted to the domain and path for which they are set and cannot be accessed by other domains for security reasons.

Cookie Security Considerations

Cookies, if not handled properly, can pose security risks:

  • HttpOnly: Marking a cookie as HttpOnly prevents JavaScript from accessing it, reducing the risk of XSS attacks.
  • Secure: Cookies marked with the Secure flag are only sent over HTTPS connections.
  • SameSite: The SameSite attribute helps prevent Cross-Site Request Forgery (CSRF) attacks by restricting how cookies are sent with cross-site requests.

Best Practices

  • Use Short-Lived Cookies: Set appropriate expiration times for cookies to minimize security risks.
  • Avoid Storing Sensitive Information: Never store sensitive data like passwords directly in cookies.
  • Use HttpOnly and Secure Flags: To protect cookies from being accessed by malicious scripts or transmitted insecurely, set the HttpOnly and Secure flags.
  • Limit Cookie Size: Ensure that cookies are kept lightweight to avoid performance issues, especially on slow networks.

Example

Here’s a simple example of setting a cookie, checking if it exists, and deleting it:

HTML
Copied
Copy To Clipboard
<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Cookies Example</title>
</head>
<body>
  <h1>JavaScript Cookies Example</h1>
  <button onclick="setCookie('username', 'JohnDoe', 365)">Set Cookie</button>
  <button onclick="alert(getCookie('username'))">Check Cookie</button>
  <button onclick="deleteCookie('username')">Delete Cookie</button>

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

    // Get a cookie
    function getCookie(name) {
      let cookieName = name + "=";
      let decodedCookie = decodeURIComponent(document.cookie);
      let cookieArray = decodedCookie.split(';');
      for(let i = 0; i < cookieArray.length; i++) {
        let cookie = cookieArray[i].trim();
        if (cookie.indexOf(cookieName) === 0) {
          return cookie.substring(cookieName.length, cookie.length);
        }
      }
      return "";
    }

    // Delete a cookie
    function deleteCookie(name) {
      document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
    }
  </script>
</body>
</html>

Conclusion

JavaScript cookies offer a simple and effective way to store data on the client-side. While they are ideal for lightweight data like session IDs and user preferences, it is important to handle them with care to ensure security and performance. By using attributes like HttpOnly, Secure, and SameSite, you can mitigate many of the risks associated with cookies and create a safer web experience for users.

πŸ‘¨β€πŸ’» Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
πŸ‘‹ Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy