Sobes.tech
Junior

What are the main features of cookies?

sobes.tech AI

Answer from AI

Cookies are small pieces of data sent by the server to the browser and stored by the browser. With each subsequent request to the same server, the browser sends these cookies back.

Main features:

  • Storage: Stored on the client side (in the browser).
  • Limited size: Usually, the size of a single cookie is limited to 4 KB. The total number of cookies per domain is also limited.
  • Identification: Used for user identification, session tracking, and saving user preferences.
  • Lifetime (Expires, Max-Age): A period can be set after which cookies will be deleted. Without an explicit lifetime, cookies are "session" cookies and are deleted when the browser is closed.
  • Scope (Domain, Path): Define for which domains and paths on the server the cookies will be sent.
  • Security (Secure, HttpOnly, SameSite):
    • Secure: Cookies are sent only over HTTPS.
    • HttpOnly: Cookies are inaccessible to JavaScript on the client side. Reduces the risk of XSS attacks.
    • SameSite: Controls the sending of cookies in cross-site requests. Protects against CSRF attacks.
  • Automatic sending: The browser automatically sends cookies to the server with each relevant request.
  • Created by server or JavaScript: Can be set via the server header Set-Cookie or through JavaScript using document.cookie.
// Setting a cookie via JavaScript
document.cookie = "username=John Doe; expires=Thu, 01 Jan 2025 00:00:00 UTC; path=/";
// Getting all cookies via JavaScript
const allCookies = document.cookie;
// Example: "cookie1=value1; cookie2=value2"
What are the main features of cookies? — Frontend - sobes.tech