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 user's browser and that the browser stores. On the next request to the same server, the browser sends these cookies back.

The operation of cookies occurs according to the following principle:

  1. Server sends cookies: When a client makes the first request to the server, the server can include a Set-Cookie header in the HTTP response. This header contains the name, value, expiration, and other attributes of the cookie.
  2. Browser saves cookies: The browser receives the HTTP response from the server, detects the Set-Cookie header, and saves the cookie data.
  3. Browser sends cookies: On subsequent requests to the same domain (or subdomains, depending on the domain attribute), the browser automatically adds a Cookie header to the HTTP request, containing the saved cookies for that domain.

Cookie attributes define their behavior:

  • Expires or Max-Age: Define the cookie's expiration time. If not set, the cookie is session-based (deleted when the browser is closed).
  • Domain: Specifies the domain for which the cookies are available.
  • Path: Specifies the path on the server for which the cookies are available.
  • Secure: Cookies are sent only over HTTPS.
  • HttpOnly: Cookies are inaccessible to scripts (e.g., JavaScript), which enhances security against XSS attacks.
  • SameSite: Defines when cookies should be sent with cross-site requests (Strict, Lax, None).

Example of a Set-Cookie header:

Set-Cookie: sessionid=abcdef123456; Expires=Wed, 30 Aug 2023 00:00:00 GMT; HttpOnly; Secure

Example of a Cookie header in a subsequent request:

Cookie: sessionid=abcdef123456

Cookies are used for:

  • Managing user sessions (login).
  • Remembering user preferences (language, theme).
  • Tracking user activity (analytics, advertising).