Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Cookies

Cookies are small pieces of data stored in the user's browser by websites. They are primarily used to remember users and their preferences, authentication tokens, and other data needed for the website to function properly. Unlike localStorage and sessionStorage, cookies have a size limit of 4KB per cookie and an expiration date that can be set by the website.

Examples

Setting a Cookie:

document.cookie = "key=value; expires=Thu, 18 Dec 2025 12:00:00 UTC; path=/";

This code sets a cookie named 'key' with the value 'value'. It also sets an expiration date for the cookie to be valid until December 18, 2025, and specifies the path where the cookie is valid.

Retrieving Cookies:

const cookies = document.cookie;

This code retrieves all cookies stored for the current website and stores them in the variable 'cookies'. Cookies are returned as a string containing key-value pairs separated by semicolons.

Removing a Cookie:

document.cookie = "key=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

This code removes the cookie named 'key' by setting its expiration date to a past time, effectively invalidating the cookie.

Use Cases

Cookies have various use cases in web applications:

  • User Authentication: Storing authentication tokens or session IDs to keep users logged in.
  • Tracking: Remembering user preferences, browsing history, or items added to a shopping cart.
  • Personalization: Customizing the user experience based on past interactions with the website.
  • Tracking Analytics: Storing information for website analytics and tracking user behavior.

Limitations

Cookies come with several limitations:

  • Size Limit: Cookies are limited to 4KB per cookie, and most browsers have a maximum limit of 50 cookies per domain.
  • Security Concerns: Cookies can be vulnerable to security risks such as cross-site scripting (XSS) attacks and cross-site request forgery (CSRF) attacks if not implemented securely.
  • Privacy Concerns: Cookies may raise privacy concerns as they can be used to track users' browsing behavior across different websites.
  • Limited Access: Cookies are accessible from both the client and server-side but are limited to the domain they were set on.