JavaScript Cookies

JavaScript cookies are small pieces of data stored in a user's web browser. They are used to store information that can be retrieved later, even if the user navigates to a different page or closes and reopens the browser. Cookies are often used to remember user preferences, track user activity, or store session-related data. Here's a more detailed explanation with examples:

Creating Cookies

Cookies are created using the document.cookie property, which allows you to set a string containing the cookie's name, value, and optional attributes like expiration date and path.

document.cookie = "username=William Mac; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";

Reading Cookies

You can access the document.cookie property to read all cookies associated with the current page. However, this property returns a single string with all the cookies, so parsing is required.

var cookies = document.cookie; // "username=William Mac; ..."

Updating Cookies

Updating a cookie involves setting a new value for the same cookie. You can use the same method as creating cookies.

document.cookie = "username=Jane Smith; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";

Deleting Cookies

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

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

Limitations and Considerations

  1. Cookies have limited storage capacity (typically around 4KB per domain).
  2. Cookies are sent with every HTTP request, which might impact performance.
  3. Cookies are not secure for sensitive data because they can be viewed and manipulated by the user.
  4. Modern web development often uses more secure methods like localStorage and sessionStorage for client-side storage.
Example Usage

A common use case for cookies is implementing a simple "Remember Me" feature on a login page:

// When user logs in and checks "Remember Me" document.cookie = "username=MacWilliam; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/"; // Later, when the user returns to the page var cookies = document.cookie; // "username=MacWilliam; ..."

In this scenario, the cookie retains the username, allowing the user to remain logged in even after closing the browser.

While cookies offer basic persistent storage, it's important to be aware of their limitations and potential security concerns.

Conclusion

JavaScript cookies are small pieces of data stored in a user's web browser that can store information like user preferences, session data, or tracking details. They are commonly used to remember data across different web pages and browser sessions. However, due to limitations and security concerns, modern web development often employs more secure alternatives like localStorage and sessionStorage.