Hack Frontend Community

What are Cookies and How to Work with Them

Cookie is small data fragment (text) that browser saves on behalf of server or client.
They're designed for storing session state, authentication, user settings and analytics.


Set-Cookie: userId=12345; Path=/; Expires=Wed, 09 Apr 2025 10:00:00 GMT;

This header tells browser: "Save cookie userId with value 12345, available across entire site (Path=/) and valid until specified date".

Where Cookies Are Used

  • Authorization and session token storage
  • User tracking (e.g., Google Analytics)
  • User settings storage (language, theme)
  • A/B testing and personalization
ParameterDescription
name=valueCookie name and value
PathLimits path for which cookie is available
DomainLimits domain (or subdomain)
ExpiresSpecifies date when cookie will be deleted
Max-AgeCookie lifetime in seconds
SecureCookie will be transmitted only over HTTPS
HttpOnlyNot accessible via document.cookie — protects from XSS
SameSiteControls behavior on cross-domain requests (Lax, Strict, None)

Security

Important:

Use Secure and HttpOnly flags for all cookies containing sensitive data, especially authorization tokens!

Reading and Deleting Cookies in JavaScript

Read

console.log(document.cookie); // "name=value; theme=dark"

Delete

To delete cookie, set expires to past:

document.cookie = "theme=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
  • Maximum ~20 cookies per domain
  • Maximum size of one cookie — ~4KB
  • Sent in every HTTP request → can increase traffic
  • Not suitable for storing large data volumes

Conclusion:

Cookie is important browser data storage mechanism, especially for sessions and security. Use them thoughtfully, following privacy and secure transmission recommendations.