Cookies

Chapter: Web APIs and Browser Integration / Section: Browser Storage

Cookies

A comprehensive guide to Cookies in Javascript. Learn about storing data in the browser with cookies, with clear explanations. Perfect for beginners starting with Javascript.

Introduction

Cookies are a fundamental part of web development, allowing websites to store small pieces of data directly in the user's browser. Understanding how to work with cookies is essential for creating personalized user experiences, maintaining user sessions, and tracking user preferences. In this guide, you'll learn the core concepts of cookies and how to implement them effectively in your Javascript applications.

Core Concepts

Cookies are key-value pairs stored in the browser. They consist of a name, a value, and optional attributes such as expiration date, path, and domain. When a server sends an HTTP response, it can include a Set-Cookie header to instruct the browser to store a cookie. On subsequent requests, the browser sends back the stored cookies to the server using the Cookie header.

Here's an example of setting a cookie in Javascript:

document.cookie = "username=JohnDoe; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/";

Implementation Details

To set a cookie in Javascript, you can use the document.cookie property. Assign a string to this property in the format name=value; attribute1=value1; attribute2=value2;.

To read a cookie, you can access document.cookie, which returns a string containing all the cookies associated with the current document. You can then parse this string to extract the desired cookie value.

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

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

Best Practices

  • Use the HttpOnly attribute to prevent client-side access to cookies containing sensitive data.
  • Set the Secure attribute to ensure cookies are only transmitted over HTTPS.
  • Specify the path attribute to limit cookie access to specific directories.
  • Encode cookie values to handle special characters and prevent injection attacks.

Common Pitfalls

  • Avoid storing sensitive information like passwords or credit card numbers in cookies.
  • Be mindful of cookie size limits, as browsers may reject cookies that are too large.
  • Consider user privacy and comply with relevant regulations like GDPR when using cookies.

Practical Examples

Here's an example of setting and reading a cookie for user preferences:

// Set a cookie for user's preferred theme document.cookie = "theme=dark; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/"; // Read the cookie value const cookieValue = document.cookie .split('; ') .find(row => row.startsWith('theme=')) .split('=')[1]; console.log(cookieValue); // Output: "dark"

Summary and Next Steps

In this guide, you learned the fundamentals of working with cookies in Javascript. You now understand how to set, read, and delete cookies, as well as best practices and common pitfalls to keep in mind. As a next step, explore more advanced topics like cookie security, cross-site scripting (XSS) prevention, and using cookies in conjunction with server-side technologies. Happy coding!