Sobes.tech
Junior

How do cookies work?

sobes.tech AI

Answer from AI

Cookies are small pieces of data that a server sends to the client's browser and stores on their device. On subsequent requests to the same server, the browser sends these cookies back.

Process:

  1. Server sending: When a client first accesses a web application, the server can include a Set-Cookie header in the HTTP response. This header contains information about cookies that the browser should save.
    // Example of Set-Cookie header in HTTP response
    Set-Cookie: sessionid=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT; Secure; HttpOnly
    
    • sessionid=abc123: Name and value of the cookie.
    • Expires: The expiration date and time of the cookie. If absent, the cookie is session-based (deleted when the browser closes).
    • Secure: Send the cookie only over HTTPS.
    • HttpOnly: Prevents access to the cookie via JavaScript (enhances security).
  2. Browser saving: The browser receives the Set-Cookie header and saves the cookies in local storage. Each cookie is associated with a specific domain and optionally a path.
  3. Browser sending: On subsequent requests to the domain for which cookies are saved, the browser automatically includes them in the HTTP request in the Cookie header.
    // Example of Cookie header in HTTP request
    Cookie: sessionid=abc123
    
  4. Server processing: The server receives cookies from the Cookie header and uses them for client identification, session state preservation, content personalization, and other purposes.

Main cookie attributes:

Attribute Description
Expires The date and time when the cookie will no longer be valid.
Max-Age The maximum lifetime of the cookie in seconds. Overrides Expires.
Domain The domain for which the cookie is valid. Defaults to the current domain.
Path The path within the domain for which the cookie is valid.
Secure Send the cookie only over secure connections (HTTPS).
HttpOnly Prevents access to the cookie via JavaScript.
SameSite Controls sending cookies with cross-site requests (CSRF protection).

Uses of cookies:

  • Session management: Saving session identifiers to maintain user state between requests.
  • Personalization: Remembering user preferences, such as language or theme.
  • Tracking: Analyzing user behavior on the site (with user consent).

Limitations:

  • Limited data size (usually about 4 KB per cookie).
  • Limited number of cookies per domain.
  • Cookies can be disabled or deleted by the user.
How do cookies work? — Frontend - sobes.tech