The Mystery of HTTP CookiesNov 2022
featured image

HTTP cookies, often simply referred to as "cookies," are small pieces of data sent from a website and stored in a user's web browser while the user is browsing. These little text files play a significant role in enhancing user experience and enabling various functionalities on websites. Let's dive into the attributes of an HTTP cookie and unveil their magic:

  • Name: The identifier for the cookie.

  • Value: The content of the cookie.

  • Domain: The domain name of the website that set the cookie.

  • Path: The URL path that must exist in the requested resource before sending the Cookie header.

  • Expires/Max-Age: Defines the lifetime of the cookie. It can either be an expiration date or a duration (in seconds).

  • Secure: Indicates if the cookie should only be transmitted over secure connections (HTTPS).

  • HttpOnly: Specifies that the cookie is inaccessible to JavaScript, enhancing security by preventing XSS attacks. (Can only be set on the server-side.)

  • SameSite: A flag that controls when cookies are sent with cross-origin requests.

Here's a simple example of setting a cookie using JavaScript:

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

In this example:

  • Name: username

  • Value: John Doe

  • Expires: Thu, 18 Feb 2024 12:00:00 UTC

  • Path: /

  • Secure: Enabled (cookie will only be transmitted over HTTPS)

  • SameSite: Set to Strict (cookie will only be sent with same-site requests)

Understanding these attributes allows developers to harness the power of cookies effectively, providing better user experiences while ensuring security and privacy standards are met. 🍪✨