Categories
JavaScript Marketing Web browsers

JavaScript Cookies: A Beginner’s Guide to Storing User Preferences and Data on Your Website

In web development, cookies are small pieces of data that are stored on a user’s computer by a website. They are used to store information about the user’s activity on the website, such as login information, shopping cart items, and preferences. Cookies can also be used to track user behavior and serve targeted advertisements. In this article, we will discuss how to use cookies in JavaScript to enhance the user experience and provide personalized content. We will cover the following topics:

  1. What are cookies?
  2. How do cookies work?
  3. Creating and accessing cookies in JavaScript
  4. Setting expiration dates for cookies
  5. Secure and HttpOnly cookies
  6. Deleting cookies
  7. Best practices for using cookies

Cookies are small text files that are created by websites and stored on a user’s computer. They contain information about the user’s activity on the website, such as login credentials, shopping cart items, and preferences. Cookies can be used to personalize the user’s experience on the website and provide targeted content.

There are two types of cookies: session cookies and persistent cookies. Session cookies are temporary and are deleted when the user closes the browser. They are used to store information about the user’s current session, such as login credentials and shopping cart items. Persistent cookies, on the other hand, are stored on the user’s computer for a specified period of time, even after the browser is closed. They are used to store information about the user’s preferences and activity on the website.

How do cookies work?

When a user visits a website, the website sends a cookie to the user’s computer. The cookie is then stored on the computer and can be accessed by the website during subsequent visits. Cookies are sent to the server with every HTTP request, which allows the server to identify the user and provide personalized content.

Cookies can be accessed and manipulated using JavaScript. This allows developers to create dynamic websites that can store and retrieve user data. Cookies can also be used to track user behavior and provide targeted advertising.

Creating and accessing cookies in JavaScript

Creating a cookie in JavaScript is simple. You can use the document.cookie property to create a new cookie. The following code creates a new cookie with the name “username” and the value “john”:

document.cookie = "username=john";

To access the value of a cookie, you can use the same document.cookie property. The following code retrieves the value of the “username” cookie:

console.log(document.cookie);

This will output the value of all cookies stored on the user’s computer. To retrieve the value of a specific cookie, you can use the following code:

function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
}

const username = getCookie("username");
console.log(username);

This code defines a function getCookie() that retrieves the value of a cookie by name. It splits the cookie string into an array of values, using the cookie name as a delimiter. It then returns the value of the cookie.

Setting expiration dates for cookies

By default, cookies are stored on the user’s computer until they are manually deleted or the browser is closed. However, you can set an expiration date for a cookie to control how long it is stored on the user’s computer. To set an expiration date for a cookie, you can add an expires attribute to the cookie string. The following code creates a cookie with an expiration date of one hour:

const now = new Date();
const time = now.getTime();
const expireTime = time + 1000 * 60 * 60; // One hour
now.setTime(expireTime);

document.cookie = `username=john; expires=${now.toUTCString()}; path=/`;

In this code, we create a new Date object and set the current time in milliseconds. We then add an hour to the current time using the getTime() method and store it in the variable expireTime. We then create a new Date object and set its time to the expiration time using the setTime() method. Finally, we create a new cookie with the name “username” and the value “john”. We set the expiration date to the value of the expireTime variable using the expires attribute. We also set the path attribute to “/” to indicate that the cookie should be available on all pages of the website.

Secure and HttpOnly cookies

Secure cookies are cookies that are only sent over an encrypted connection (HTTPS). This ensures that the cookie data is protected from unauthorized access. To create a secure cookie, you can add the Secure attribute to the cookie string. The following code creates a secure cookie with the name “username” and the value “john”:

document.cookie = "username=john; Secure";

HttpOnly cookies are cookies that can only be accessed by the server and not by JavaScript. This protects the cookie data from cross-site scripting (XSS) attacks. To create an HttpOnly cookie, you can add the HttpOnly attribute to the cookie string. The following code creates an HttpOnly cookie with the name “username” and the value “john”:

document.cookie = "username=john; HttpOnly";

Deleting cookies

To delete a cookie, you can set its expiration date to a date in the past. This will cause the cookie to be immediately deleted from the user’s computer. The following code deletes the “username” cookie:

const now = new Date();
now.setTime(now.getTime() - 1);
document.cookie = "username=; expires=" + now.toUTCString() + "; path=/";

In this code, we create a new Date object and set its time to one millisecond before the current time using the setTime() method. We then create a new cookie with the name “username” and set its expiration date to the past using the expires attribute. This causes the cookie to be immediately deleted from the user’s computer.

Best practices for using cookies

When using cookies in JavaScript, there are a few best practices to keep in mind:

  • Only store essential information in cookies: Cookies should only be used to store essential information, such as login credentials, shopping cart items, and preferences. Storing sensitive information, such as credit card numbers, in cookies is not secure and should be avoided.
  • Use secure and HttpOnly cookies: Secure and HttpOnly cookies provide additional security and protection against attacks. Always use these attributes when creating cookies.
  • Set expiration dates for cookies: Setting expiration dates for cookies helps to ensure that they are not stored on the user’s computer indefinitely. This helps to protect the user’s privacy and reduces the risk of data breaches.
  • Provide clear information about the use of cookies: It is important to provide clear information to users about the use of cookies on your website. This includes information about what data is being collected, how it is being used, and how users can opt out if they choose to do so.

JavaScript Cookies

Cookies are a powerful tool in web development that can be used to store information about the user’s preferences and behavior on a website. JavaScript provides a simple and easy-to-use API for creating, reading, and deleting cookies. However, it is important to use cookies responsibly and follow best practices to ensure the security and privacy of the user’s data.

In this article, we have covered the basics of using cookies in JavaScript, including creating and reading cookies, setting expiration dates, and using secure and HttpOnly cookies. We have also discussed how to delete cookies and provided some best practices for using cookies in web development.

By following these best practices, you can create a more secure and user-friendly website that provides a personalized experience for your users while protecting their privacy and data. As always, it is important to stay up to date on the latest developments in web development and security to ensure that your website is always up to date and secure.