JavaScript tutorials > Web APIs and the DOM > Browser APIs > What are cookies and how do you manipulate them with JavaScript?

What are cookies and how do you manipulate them with JavaScript?

Cookies are small text files that websites store on a user's computer to remember information about them, such as login details, preferences, or shopping cart contents. This tutorial explores how to manipulate cookies using JavaScript, covering reading, writing, updating, and deleting cookies.

Understanding Cookies

Cookies are essentially key-value pairs stored in the user's browser. They are associated with a specific domain and path. When the browser makes a request to the server for that domain and path, the browser automatically includes the cookies in the request headers. Cookies can have expiration dates; if an expiration date is set, the cookie will be automatically deleted by the browser after that date. If no expiration date is set, the cookie is considered a session cookie and will be deleted when the browser is closed.

Setting a Cookie with JavaScript

The document.cookie property is the primary way to manipulate cookies in JavaScript. Setting a cookie involves assigning a string to this property. This string should follow a specific format:

name=value; expires=expiration_date; path=path

  • name: The name of the cookie.
  • value: The value of the cookie.
  • expires: (Optional) The expiration date of the cookie in UTC format. If not specified, the cookie will be a session cookie.
  • path: (Optional) The path for which the cookie is valid. Defaults to the current directory of the page. Setting path=/ makes the cookie available for the entire domain.

In the example above, we set a cookie named username with the value John Doe. The cookie will expire on December 18, 2024, and is valid for the entire domain.

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2024 12:00:00 UTC; path=/";

Reading Cookies with JavaScript

Reading cookies is also done through the document.cookie property. However, when reading, it returns a string containing all cookies for the current document, separated by semicolons. To get the value of a specific cookie, you need to parse this string.

The example above reads all cookies and logs them to the console. Note that this will print a string containing all cookies concatenated together.

let cookies = document.cookie;
console.log(cookies); // Output: username=John Doe; otherCookie=someValue

Parsing Cookies to Extract a Specific Value

This function getCookie(name) parses the document.cookie string to retrieve the value of a cookie with the specified name.

  1. It splits the cookie string into an array of individual cookies using the semicolon as a delimiter.
  2. It iterates through the array, trimming whitespace from each cookie string.
  3. For each cookie, it checks if it starts with the specified name followed by an equals sign.
  4. If it finds a match, it extracts the value of the cookie (the part after the equals sign) and returns it.
  5. If no cookie with the specified name is found, it returns null.

function getCookie(name) {
  const cookieString = document.cookie;
  const cookiesArray = cookieString.split(';');

  for (let i = 0; i < cookiesArray.length; i++) {
    let cookie = cookiesArray[i].trim();
    // Does this cookie string begin with the name we want?
    if (cookie.startsWith(name + '=')) {
      return cookie.substring(name.length + 1);
    }
  }
  return null;
}

let username = getCookie("username");
console.log(username); // Output: John Doe

Updating a Cookie

Updating a cookie is the same as setting a cookie. You simply set a new cookie with the same name, but a different value and/or expiration date.

In the example above, we update the username cookie to Jane Doe. Make sure you include the path attribute, since omitting it might result in the cookie not being updated correctly, especially if the original cookie was set with a specific path.

document.cookie = "username=Jane Doe; expires=Thu, 18 Dec 2024 12:00:00 UTC; path=/";

Deleting a Cookie

To delete a cookie, you set its expiration date to a past date. The browser will then automatically remove the cookie.

In the example above, we set the expiration date of the username cookie to January 1, 1970, effectively deleting it. Again, ensuring the path attribute matches the original cookie's path is crucial for successful deletion.

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

Concepts Behind the Snippet

The key concepts behind cookie manipulation in JavaScript involve understanding the document.cookie property, the format of cookie strings, and the importance of the expires and path attributes. Cookies are client-side data storage mechanisms that allow websites to persist information across multiple requests. Because they are sent with every HTTP request, it's crucial to be mindful of their size and the amount of data stored within them to avoid performance issues.

Real-Life Use Case Section

Cookies are frequently used for:

  • Authentication: Storing user login status.
  • Personalization: Remembering user preferences, such as language or theme settings.
  • Shopping Carts: Maintaining a list of items a user has added to their cart.
  • Tracking: Analyzing user behavior on a website.

For example, an e-commerce site might use cookies to remember a user's shopping cart items. When the user returns to the site, the cookies are read, and the shopping cart is automatically populated with the previously selected items.

Best Practices

  • Security: Avoid storing sensitive information in cookies, such as passwords or credit card details. If you must store sensitive data, encrypt it before storing it in the cookie. Consider using the Secure attribute to ensure the cookie is only transmitted over HTTPS.
  • Size: Keep cookies small to minimize the impact on website performance. Browsers typically limit the size of individual cookies and the total number of cookies a website can store.
  • Expiration: Set appropriate expiration dates for cookies. Avoid setting very long expiration dates unless absolutely necessary. Session cookies are preferred for temporary data.
  • Path and Domain: Be specific with the path and domain attributes to limit the scope of the cookie.
  • HttpOnly: Set the HttpOnly attribute to prevent client-side scripts from accessing the cookie, reducing the risk of cross-site scripting (XSS) attacks (This needs to be set server-side).
  • SameSite: Set the SameSite attribute to control how cookies are sent with cross-site requests, providing protection against cross-site request forgery (CSRF) attacks (This needs to be set server-side).

Interview Tip

When discussing cookies in an interview, be sure to emphasize your understanding of:

  • The purpose of cookies and their role in web development.
  • How to read, write, update, and delete cookies using JavaScript.
  • Security best practices for handling cookies, including the importance of the Secure, HttpOnly, and SameSite attributes.
  • Alternative storage options, such as localStorage and sessionStorage, and their differences from cookies.

Be prepared to discuss the limitations of cookies and the situations where alternative storage mechanisms might be more appropriate.

When to Use Them

Use cookies when you need to store small amounts of data that need to be transmitted with every HTTP request. They are suitable for:

  • Authentication tokens.
  • Personalization settings.
  • Tracking user sessions.
  • Remembering shopping cart contents.

Avoid using cookies for large amounts of data or sensitive information that doesn't need to be transmitted with every request. In those cases, consider using localStorage, sessionStorage, or server-side storage mechanisms.

Memory Footprint

Cookies have a relatively small memory footprint. However, because they are sent with every HTTP request, excessive use of large cookies can negatively impact website performance. Browsers typically limit the size of individual cookies (around 4KB) and the total number of cookies a website can store (around 50 per domain).

It's important to monitor the size and number of cookies used on your website to ensure they don't become a performance bottleneck.

Alternatives

Alternatives to cookies include:

  • localStorage: Stores data persistently in the browser, with no expiration date. Data is only accessible to the origin that stored it. Suitable for storing larger amounts of data than cookies.
  • sessionStorage: Stores data for only one session. The data is deleted when the browser tab or window is closed. Data is only accessible to the origin that stored it.
  • IndexedDB: A more complex NoSQL database that provides transactional support and allows you to store larger amounts of structured data client-side.
  • Server-side Sessions: Store session data on the server and use a session ID (typically stored in a cookie) to identify the user's session. This is generally more secure for storing sensitive data.

Pros

  • Widely Supported: Cookies are supported by all major browsers.
  • Simple API: The document.cookie property provides a simple API for reading and writing cookies.
  • Automatic Transmission: Cookies are automatically sent with every HTTP request to the server.

Cons

  • Limited Size: Cookies have a limited size (around 4KB).
  • Security Risks: Cookies can be vulnerable to cross-site scripting (XSS) and cross-site request forgery (CSRF) attacks.
  • Performance Impact: Large cookies can negatively impact website performance.
  • Privacy Concerns: Cookies can be used to track user behavior, raising privacy concerns.

FAQ

  • What is the maximum size of a cookie?

    The maximum size of a cookie is approximately 4KB.
  • How do I make a cookie secure?

    To make a cookie secure, use the Secure attribute to ensure it's only transmitted over HTTPS. Server-side, set the HttpOnly attribute to prevent client-side scripts from accessing it, and use the SameSite attribute to protect against CSRF attacks.
  • Are cookies the only way to store data client-side?

    No, there are other options, such as localStorage, sessionStorage, and IndexedDB. Each option has its own advantages and disadvantages, depending on the specific use case.