A cookie is a small piece of data sent from a website and stored on a user's computer by a web browser (in plain text format).
The browser sends cookies back to the server with each subsequent request, allowing the server to determine whether the request came from the same browser or not. By analyzing the cookie data, the server can identify the user's session and track the user's actions on the site.
Cookies are mainly used for three purposes:
User session management (user authentication, storing shopping carts, etc)
Tracking users (recording and analyzing user behavior by web analytics tools)
Personalization (storing user preferences and site settings for particular device/browser)
How it works
The server sends cookies to the browser by adding the "Set-Cookie: cookie-name = cookie-value" HTTP header to the response. The server can send multiple cookies by adding multiple Set-Cookie headers.
Browsers send cookies to the server by adding "Cookie: saved-cookie" header to the request. If multiple cookies exist for a web page, they are sent in a single 'Cookie' header and separated by a semicolon.
Browser Request With Cookie Header
GET / HTTP/1.1
Cookie: theme=light; authToken=Fb2#[email protected];
If the server does not provide information about the expiration of the cookie by specifying the exact date or after a certain period of time (no Expires or Max-Age directives), it becomes a session cookie (in-memory cookie) and is deleted when the user closes the browser.
Secure cookies can only be transmitted over HTTPS protocol and will not be transmitted over insecure HTTP. This reduces the likelihood that a cookie will be stolen. But even with the Secure directive, cookies are still insecure, and no confidential information should be stored in cookies.
Use the Same-Site directive to protect cookies from cross-site request forgery (CSRF) attacks. The 'SameSite=Strict' directive instructs the browser to send cookies only to the same site on which they are set. If the request came from a different site, none of the cookies marked with the Strict attribute will be included in the request. Unlike Strict, the 'SameSite=None' directive tells the browser to send cookies with both cross-site requests and same-site requests.
The Domain and Path attributes define the scope of the cookie. For security reasons, cookies can only be set on the current site's top domain and its sub domains. For example, the site1.com cannot set a cookie for site2.com because this would allow the site1.com to control the cookies of site2.com.