Junior
What are the main features of using cookies?
sobes.tech AI
Answer from AI
- Client-side data storage: Cookies are stored in the user's browser.
- Sent with each request to the server: With each request to the domain that set the cookie, it is automatically sent via the
CookieHTTP header. - Size limit: The size of a single cookie is usually limited (often 4KB), and there is also a limit on the total number of cookies per domain.
- Lifetime: The lifetime of a cookie is set when it is created (
ExpiresorMax-Age) or it exists until the browser is closed (session cookie). - Security:
HttpOnly: Prevents access to the cookie from JavaScript, protecting against XSS attacks.Secure: Sends the cookie only over HTTPS connections.SameSite: Controls the sending of cookies with cross-site requests, preventing CSRF attacks.
- Management: Cookies can be managed on the server side (via the
Set-Cookieheader) and on the client side (viadocument.cookie), if theHttpOnlyflag is not set. - Usage: Sessions, personalization, activity tracking.
// Getting all available cookies
const allCookies = document.cookie;
// Setting a new cookie
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/";
// Deleting a cookie (setting expiration in the past)
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";